diff --git a/README.md b/README.md
index 4356fcfde46010b352c82a00e397e71761b1f51a..9519c8900cfdf7af92be2d1616e5d9d795f80199 100644
--- a/README.md
+++ b/README.md
@@ -1,37 +1,37 @@
-# leak analysis
-
-
-Python-Programme für die Auswertung und Erstellung von Kalibrierscheinen ( TL1, TL2)
-
-# writeLaTex-ks-TL1.py:
-
-Erstellung eines Kalibrierscheins für TL1 , nur das Tex-Dokument
-
-# writeLaTex-ks-TL2.py:
-
-Erstellung eines Kalibrierscheins für TL2 , nur das Tex-Dokument
-
-# attachment_cer.py:
-
-Kalibrierscheine werden an das cer-dokument angehängt
-
-
-# attachment_bur.py:
-
-Manuelle veränderte Versandaufträge und Gefahrenstoffe werden an das bur-dokument angehängt
-
-# API-V2-elab.py:
-
-Messwerte werden in das Laborbuch übertragen
-
-
-# file-to-couchdb_tl1_cL.py:
-
-Die Werte aus dem Messprogramm TL1 werden in das cal-dokument übertragen
-
-# file-to-couchdb_tl2.py:
-
-Die Werte aus dem Messprogramm TL1 werden in das cal-dokument übertragen
-
-Genaue Erklärung folgt:
-
+# leak analysis
+
+
+Python-Programme für die Auswertung und Erstellung von Kalibrierscheinen ( TL1, TL2)
+
+# writeLaTex-ks-TL1.py:
+
+Erstellung eines Kalibrierscheins für TL1 , nur das Tex-Dokument
+
+# writeLaTex-ks-TL2.py:
+
+Erstellung eines Kalibrierscheins für TL2 , nur das Tex-Dokument
+
+# attachment_cer.py:
+
+Kalibrierscheine werden an das cer-dokument angehängt
+
+
+# attachment_bur.py:
+
+Manuelle veränderte Versandaufträge und Gefahrenstoffe werden an das bur-dokument angehängt
+
+# API-V2-elab.py:
+
+Messwerte werden in das Laborbuch übertragen
+
+
+# file-to-couchdb_tl1_cL.py:
+
+Die Werte aus dem Messprogramm TL1 werden in das cal-dokument übertragen
+
+# file-to-couchdb_tl2.py:
+
+Die Werte aus dem Messprogramm TL1 werden in das cal-dokument übertragen
+
+Genaue Erklärung folgt:
+
diff --git a/attachment_bur.py b/attachment_bur.py
deleted file mode 100644
index f9dde674317a6b8dfaac78987a0c4d559cd19b82..0000000000000000000000000000000000000000
--- a/attachment_bur.py
+++ /dev/null
@@ -1,116 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Created on Tue Mar 19 15:11:54 2024
-
-@author: becker07
-"""
-
-import pathlib
-import os
-
-import couchdb 
-
-
-couch = couchdb.Server('http://a73434.berlin.ptb.de:5984')
-db = couch['vl_db'] # existing
-
-
-########## Vorgangsnummer und Jahr angeben  #########
-vn = "10"
-year = "24"
-
-
-bur = "bur-7.5-1V-" + year + "-" + vn
-print(bur)
-
-doc = db.get(bur)
-
-sign = doc["Bureaucracy"]["Customer"]["Sign"]
-sign = sign.lower()
-
-
-########### Schedule Date finden  ##############
-
-n = 1000
-i = 0
-while i <= n:
-    date_type=doc["Bureaucracy"]["Date"][i]["Type"]
-    date=doc["Bureaucracy"]["Date"][i]["Value"]
-    if date_type == 'schedule':
-        i=n
-    i = i + 1
-print (date_type,date )
-i = 0
-
-
-##################################################################
-
-vn_np=float(vn)
-if vn_np < 100:
-    if vn_np < 10:
-        vn_str = '00'+ vn
-    else:
-        vn_str = '0'+ vn
-else:
-    vn_str =  vn
-
-print(vn_str)
-
-vs= 'shipping-' + sign + '-' + vn_str + '-' + date 
-dang= 'dangerousgoods-' + sign + '-' + vn_str + '-' + date 
-
-print(vs,dang)
-
-
-#dangerousgoods-alc-010-2024-01-22
-
-vs_pdf= vs + ".pdf"
-vs_tex= vs + ".tex"
-#print(cer_pdf, cer_tex)
-ship_pdf = "C:\\Users\\becker07\\ptb-latex\\versandauftrag\\" + vs_pdf
-ship_tex = "C:\\Users\\becker07\\ptb-latex\\versandauftrag\\" + vs_tex
-
-
-dg_pdf= dang + ".pdf"
-dg_tex= dang + ".tex"
-#print(cer_pdf, cer_tex)
-dang_pdf = "C:\\Users\\becker07\\ptb-latex\\gefahrgutformular\\" + dg_pdf
-dang_tex = "C:\\Users\\becker07\\ptb-latex\\gefahrgutformular\\" + dg_tex
-
-
-###################  Versand, Gefahrenstoffe werden an das bur-json-dokument angehangen ##################
-
-content_ship_pdf=pathlib.Path(ship_pdf).read_bytes() 
-content_ship_tex=pathlib.Path(ship_tex).read_bytes() 
-db.put_attachment(doc, content_ship_pdf, vs_pdf , content_type='application/pdf')
-db.put_attachment(doc, content_ship_tex, vs_tex , content_type='text/plain')
-
-content_dang_pdf=pathlib.Path(dang_pdf).read_bytes() 
-content_dang_tex=pathlib.Path(dang_tex).read_bytes() 
-db.put_attachment(doc, content_dang_pdf, dg_pdf , content_type='application/pdf')
-db.put_attachment(doc, content_dang_tex, dg_tex , content_type='text/plain')
-        
-
-    
-   
-###################  die Kalibrierscheine werden im Ordner Kalibrierscheine gelöscht ################## 
-   
-#cer_pdf= "ks-" +cers[i] + "-" + year + ".pdf"
-#cer_tex= "ks-" +cers[i] + "-" + year + ".tex"
-#cer_aux= "ks-" +cers[i] + "-" + year + ".aux"
-#cer_log= "ks-" +cers[i] + "-" + year + ".log"
-#cer_gz= "ks-" +cers[i] + "-" + year + ".synctex.gz"
-#print(cer_pdf, cer_tex)
-#ks_pdf = "C:\\Users\\becker07\\kalibrierschein\\" + cer_pdf
-#ks_tex = "C:\\Users\\becker07\\kalibrierschein\\" + cer_tex
-#ks_aux = "C:\\Users\\becker07\\kalibrierschein\\" + cer_aux
-#ks_log = "C:\\Users\\becker07\\kalibrierschein\\" + cer_log
-#ks_gz = "C:\\Users\\becker07\\kalibrierschein\\" + cer_gz
-    
-#print(ks_pdf, ks_tex)
-#os.remove(ks_pdf)
-#os.remove(ks_tex)
-#os.remove(ks_aux)
-#os.remove(ks_log)
-#os.remove(ks_gz)
-        
diff --git a/attachment_cer.py b/attachment_cer.py
index 3e23f079b3b56ad278c9cfdb2fd5063549d8c3a9..49d7d2387f508c512d582e034c3846db67cbfac9 100644
--- a/attachment_cer.py
+++ b/attachment_cer.py
@@ -7,27 +7,57 @@ Created on Fri Jan  6 11:14:44 2023
 
 import pathlib
 import os
-
 import couchdb 
+try:
+    from configparser import ConfigParser
+except ImportError:
+    from ConfigParser import ConfigParser  # ver. < 3.0
+
+
+configtl1 = ConfigParser()
+ini_values = ConfigParser()
+# parse existing file
+configtl1.read('tl1.ini')
+ini_values.read('inputs.ini')
+# read values from a section
+
+cal_cert = ini_values.get('input_cer', 'cal_cert')
+year = ini_values.get('input_gen',  'year')
+year_str2=year[2:]
+no = ini_values.get('input_gen', 'no')
+path=configtl1.get('path', 'path')
+server=configtl1.get('couch', 'couch')
+db_vl=configtl1.get('couch', 'db')
+
+couch = couchdb.Server(server)
+db = couch[db_vl] # existing
+
+RefNo = ini_values.get('bur', 'RefNo')   
 
+RefNo='bur-7.5-1V-' + year_str2 + '-' + RefNo  
 
-couch = couchdb.Server('http://a73434.berlin.ptb.de:5984')
-db = couch['vl_db'] # existing
+print(RefNo)
 
+doc_RefNo = db.get(RefNo)
 
-year = "2024"
+cers =doc_RefNo["Bureaucracy"]["Certificate"]
 
-cers = ["75552","75553"]    #  Beispiel: cers = ["75511_0001","75512_0001"] 
+
+
+#cers = ["75552","75553"]    #  Beispiel: cers = ["75511_0001","75512_0001"] 
 #cers = ["75562","75563"]    #  Beispiel: cers = ["75511_0001","75512_0001"] 
 
 ###################  die Kalibrierscheine werden an das cer-json-dokument angehangen ##################
-i = 0
-while i < len(cers):
-    json_file = "cer-" + year + '-' + cers[i] 
+
+
+for cers_i in cers:
+    print(cers_i)
+    cers_i=str(cers_i) 
+    json_file = "cer-" + year + '-' + cers_i
     print(json_file)
     doc = db.get(json_file)
-    cer_pdf= "ks-" +cers[i] + "-" + year + ".pdf"
-    cer_tex= "ks-" +cers[i] + "-" + year + ".tex"
+    cer_pdf= "ks-" +cers_i + "-" + year + ".pdf"
+    cer_tex= "ks-" +cers_i + "-" + year + ".tex"
     print(cer_pdf, cer_tex)
     ks_pdf = "C:\\Users\\becker07\\kalibrierschein\\" + cer_pdf
     ks_tex = "C:\\Users\\becker07\\kalibrierschein\\" + cer_tex
@@ -37,21 +67,21 @@ while i < len(cers):
     db.put_attachment(doc, content_pdf, cer_pdf , content_type='application/pdf')
     db.put_attachment(doc, content_tex, cer_tex , content_type='text/plain')
         
-    i += 1
+   
     
    
 ###################  die Kalibrierscheine werden im Ordner Kalibrierscheine gelöscht ################## 
    
-i = 0
-while i < len(cers):
-    json_file = "cer-" + year + '-' + cers[i] 
+for cers_i in cers:
+    cers_i=str(cers_i) 
+    json_file = "cer-" + year + '-' + cers_i 
     print(json_file)
     doc = db.get(json_file)
-    cer_pdf= "ks-" +cers[i] + "-" + year + ".pdf"
-    cer_tex= "ks-" +cers[i] + "-" + year + ".tex"
-    cer_aux= "ks-" +cers[i] + "-" + year + ".aux"
-    cer_log= "ks-" +cers[i] + "-" + year + ".log"
-    cer_gz= "ks-" +cers[i] + "-" + year + ".synctex.gz"
+    cer_pdf= "ks-" + cers_i + "-" + year + ".pdf"
+    cer_tex= "ks-" + cers_i + "-" + year + ".tex"
+    cer_aux= "ks-" + cers_i + "-" + year + ".aux"
+    cer_log= "ks-" + cers_i + "-" + year + ".log"
+    cer_gz= "ks-" + cers_i + "-" + year + ".synctex.gz"
     print(cer_pdf, cer_tex)
     ks_pdf = "C:\\Users\\becker07\\kalibrierschein\\" + cer_pdf
     ks_tex = "C:\\Users\\becker07\\kalibrierschein\\" + cer_tex
@@ -66,4 +96,4 @@ while i < len(cers):
     os.remove(ks_log)
     os.remove(ks_gz)
         
-    i += 1
\ No newline at end of file
+    
\ No newline at end of file
diff --git a/config.json b/config.json
new file mode 100644
index 0000000000000000000000000000000000000000..4adebe0173cd221590b8e9672512cb0aea7bf263
--- /dev/null
+++ b/config.json
@@ -0,0 +1,12 @@
+{
+	"Pfad":
+	{
+		"Messwerte": "/home/friske01/O/Vakuum/Messplaetze/TL2/Messwerte/",
+		"Kalibrierschein": "/home/friske01/KS/"
+	},
+	"KS-Daten":
+	{
+		"Jahr": 2024,
+		"lfd. Nr.": 1
+	}
+}
diff --git a/file-to-couchdb_TLA.py b/file-to-couchdb_TLA.py
index c4909cfe8a14860227f45561c88ba643cb0e55d7..7a2a3e87847fa8fc358bbb8a4b207ac8ff9e69c5 100644
--- a/file-to-couchdb_TLA.py
+++ b/file-to-couchdb_TLA.py
@@ -28,7 +28,9 @@ db = couch['vl_db'] # existing
 
 
 
+
 cal_cert = "75559"
+
 year = "2024"
 no = "0001"
 
diff --git a/file-to-couchdb_TLV_cL.py b/file-to-couchdb_TLV_cL.py
deleted file mode 100644
index 36bc1b344260981063242b02a8b8509e40241bce..0000000000000000000000000000000000000000
--- a/file-to-couchdb_TLV_cL.py
+++ /dev/null
@@ -1,669 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Created on Fri Jul  1 12:12:37 2022
-
-@author: becker07
-"""
-import sys
-import numpy as np
-import couchdb 
-import pandas as pd
-import json
-import csv
-import re
-from matplotlib import pyplot as plt
-import pathlib
-
-couch = couchdb.Server('http://a73434.berlin.ptb.de:5984')
-db = couch['vl_db'] # existing
-
-
-## Eingabe von:
-#    - Kalibrierscheinnummer
-#    - Jahr der Kalibrierung 
-#    - laufende Nummer der Kalibrierung
-
-
-
-cal_cert = "75573"
-year = "2024"
-no = "0001"
-QMS="ja"   ######### ja beim Scan
-kk_ik_pn= "kk" ######## kk,ik oder pn
-
-
-
-json_file = "cal-" + year + "-fm1-kk-" + cal_cert + "_" + no
-doc = db.get(json_file) 
-print(json_file)
-
-
-dateiTab = cal_cert 
-#print(dateiTab)
-
-
-dateiTab=pd.read_csv(dateiTab,  sep="\t", decimal = ',' )
-
-L_ar=dateiTab["L"]
-print('Leitwert j= 1, nein = 0 :: ', L_ar)
-
-L=L_ar[0]
-print('Leitwer : ',L)
-
-
-gauge = float(doc["Calibration"]["CustomerObject"]["Setup"]["CDG"])
-print(gauge)
-
-fileQMS = "QMS" +  cal_cert + ".txt" 
-dateiQMS =fileQMS
-ScanQMS="Scan"+cal_cert + ".txt"
-ScanOffsQMS="Scan_Offs"+cal_cert + ".txt"
-print(ScanQMS)
-
-# Die Daten aus dem File mit der entsprechenden Kalibrierscheinnummer werden eingelesen:
-# datum, time, p_up und alle Temperaturen, 
-
-
-#datei = "N:\Abt_7\Fb75\Vakuum\Messplaetze\TL1\Kalibrierungen\\22\\TP7464.txt"
-
-if L == 1 :
-    
-    
-    m1=dateiTab["m1"]
-    m2=dateiTab["m2"]
-    m3=dateiTab["m3"]
-    m4=dateiTab["m4"]
-
-    t1=dateiTab["t1"]
-    t2=dateiTab["t2"]
-    t3=dateiTab["t3"]
-    t4=dateiTab["t4"]
-    time1=dateiTab["time1"]
-    time2=dateiTab["time2"]
-    time3=dateiTab["time3"]
-
-    pmean=dateiTab["p-mean"]*100
-    pmin=dateiTab["p-min"]*100
-    pmax=dateiTab["p-max"]*100
-    
-
-    h=dateiTab["distance"]
-    
-       
-    print("Constantes Volumen",h)
-    
-                               
-                                                                
-else:
-    print("Constanter Leitwert")
-
-
-datum=dateiTab["Datum"]
-time=dateiTab["Zeit"]
-gas=dateiTab["Gasart"]
-
-if gauge== 0.01 :
-    p_offs_01=dateiTab["p-offset"]*100
-    p_fill_01=dateiTab["p-fill "]*100
-    p_fill_srg=dateiTab["p-max"]
-    p_offs_srg=dateiTab["p-min"]
-    
-else :
-    p_offs=dateiTab["p-offset"]*100
-    p_fill=dateiTab["p-fill "]*100
-#p_fill=np.genfromtxt(dateiTab,skip_header=1,delimiter='\t',usecols=(5))
-
-p_ig=dateiTab["Kommentar"]
-T_room=dateiTab["T-Raum"]
-T_fm=dateiTab["T-FM"]
-T_tl1=dateiTab["T-TL1"]
-T_tl2=dateiTab["T-TL2"]
-T_tl3=dateiTab["T-TL3"]
-T_tl4=dateiTab["T-TL4"]
-
-#print(T_fm,T_room,T_tl1, T_tl2,T_tl3,T_tl4)
-
-
-I_TL_time=dateiTab["Time-TL"]
-I_Offs_time=dateiTab["Time-offset"]
-I_FM_time=dateiTab["Time-FM"]
-
-#print(I_TL_time,I_Offs_time,I_FM_time)
-
-Valve=dateiTab["Ventil"]
-
-
-if QMS == "ja" :
-    I_TL_time=dateiTab["Time-TL"]
-    I_Offs_time=dateiTab["Time-offset"]
-    I_FM_time=dateiTab["Time-FM"]
-
-    #print(I_TL_time,I_Offs_time,I_FM_time)
-
-
-####################### Der Scan des QMS ##############################################################################
-
-
-
-##############  die leeren Zeilen und Überschriften werden gelöscht  ###################
-
-    with open(ScanQMS, "r") as fp:
-        tab=fp.read()
-
-    with open('ScanQMS.txt', 'w') as fp:
-        fp.write(tab) 
-        
-    with open(ScanOffsQMS, "r") as fp:
-        tab=fp.read()
-
-    with open('ScanOffsQMS.txt', 'w') as fp:
-        fp.write(tab)
-
-
-    del_def = []
-    with open('ScanQMS.txt', "r") as fp:
-        del_def = fp.readlines()
-        with open('ScanQMS.txt', "w") as fp:
-            for number, line in enumerate(del_def):
-                if number not in [0, 1,6,7,22,23,24,25,47,48]:
-                    fp.write(line)
-            
-            del_def = []
-            with open('ScanOffsQMS.txt', "r") as fp:
-                del_def = fp.readlines()
-                with open('ScanOffsQMS.txt', "w") as fp:
-                    for number, line in enumerate(del_def):
-                        if number not in [0, 1,6,7,22,23,24,25,47,48]:
-                            fp.write(line)
-
-
-
-
-###########  Scan #####################
-
-    with open('ScanQMS.txt','r') as file:
-        tab=file.read()
-        lstdef=tab.rfind("Channel count")+16
-        lsttab=tab.rfind("Scan Data (Pressures in mbar)")+32
-        filetab=tab[lsttab:]                                       ### Das File wird getrennt und die Tabelle mit den Messwerten in das filetab übergeben
-        filedef=tab[:lstdef]                                       ### Das File wird getrennt und die Einstellungen und Infos in filedef übergeben
-    
-    
-    with open('QMS-Def.txt', 'w') as f:
-        f.write(filedef)
-    
-    
-    df_tab = pd.read_csv("QMS-Def.txt",
-                         sep="\t",
-                         #usecols=["Time"]
-                         header=None,
-                         )
-
-    def_key=np.array(df_tab[0])
-    l=len(def_key)
-    print(l)
-    #def_key=np.delete(def_key, l-1)
-    def_value=np.array(df_tab[1], dtype=str)
-    #def_value=np.delete(def_value, l-1)
-    
-
-   
-    with open('QMS-Scan.txt', 'w') as f:
-        f.write(filetab)    
-        df = pd.read_csv("QMS-Scan.txt",
-                         sep="\t",
-                         #usecols=["Time"]
-                         header=None,
-                         )
-        df=df.replace(np.nan, 0)
-
-
-    l=len(df)
-
-    print(l)
-
-    mass_no=np.array(df[0:1])
-    mass_unit=mass_no[0]
-    
-    
-   
-
-    if l == 3:
-        mass_value=np.array(df[1:2])
-        mass_value=mass_value[0]
-        print(mass_value())
-    else:
-        mass_value=np.array(df[l-2:l-1])
-        mass_value=mass_value[0]
-        
-
-    
-#############################################################################################################
-###########  Scan Offset   #####################
-
-    with open('ScanOffsQMS.txt','r') as file:
-        tab_offs=file.read()
-        lstdef_offs=tab_offs.rfind("Channel count")+16
-        lsttab_offs=tab_offs.rfind("Scan Data (Pressures in mbar)")+32
-        filetab_offs=tab_offs[lsttab_offs:]                                       ### Das File wird getrennt und die Tabelle mit den Messwerten in das filetab übergeben
-        filedef_offs=tab_offs[:lstdef_offs]                                       ### Das File wird getrennt und die Einstellungen und Infos in filedef übergeben
-    
-    
-    with open('QMS_Offs-Def.txt', 'w') as f:
-        f.write(filedef_offs)
-    
-    
-    df_tab_offs = pd.read_csv("QMS_Offs-Def.txt",
-                         sep="\t",
-                         #usecols=["Time"]
-                         header=None,
-                         )
-
-    def_key_offs=np.array(df_tab_offs[0])
-    l=len(def_key_offs)
-    def_value_offs=np.array(df_tab_offs[1], dtype=str)
-    #def_value=np.delete(def_value, l-1)
-    
-
-   
-    with open('QMS_Offs-Scan.txt', 'w') as f:
-        f.write(filetab_offs)    
-        df_offs = pd.read_csv("QMS_Offs-Scan.txt",
-                         sep="\t",
-                         #usecols=["Time"]
-                         header=None,
-                         )
-        df_offs=df_offs.replace(np.nan, 0)
-
-
-    l=len(df_offs)
-
-    print(l)
-
-       
-
-    if l == 3:
-        mass_value_offs=np.array(df_offs[1:2])
-        mass_value_off=mass_value_offs[0]
-        print(mass_value_offs())
-    else:
-        mass_value_offs=np.array(df_offs[l-2:l-1])
-        mass_value_off=mass_value_offs[0]
-    
-
-#############################################################################################################
-
-###################### Plot der Scans werden abgebildet und den json-dokument hinzugefügt #####################
-I_Scan=np.float64(mass_value[2:-2])
-I_Scan_Offs=np.float64(mass_value_off[2:-2])
-Mass_Scan=mass_no[0]
-Mass_Scan=Mass_Scan[2:-2]
-
-for i in range(len(Mass_Scan)):
-    Mass_Scan[i] = re.sub(r"Mass ", "", Mass_Scan[i]).strip()
-   
-   
-Mass_Scan=np.float64(Mass_Scan)
-
-fig=plt.figure()
-ax=fig.add_axes([0,0,4,2])
-ax.set_xlabel('Masse')
-ax.set_ylabel('QMS-Signal')
-ax.set_yscale('log')
-#plt.plot(1010,4.65e-10, 'bo')
-plt.plot(Mass_Scan,I_Scan, label=r'Floww')
-plt.plot(Mass_Scan,I_Scan_Offs,label=r'Offset' )
-plt.legend()
-
-
-plt.grid()
-
-fig.savefig("Scan.pdf", bbox_inches='tight')
-
-
-
-#############################################################################################################
-
-from collections import OrderedDict
-
-def getMassAverage(filename, tbegin = None, tend = None, trange = None):
-    def error_exit(x):
-        print('ERROR: ', str(x), file=sys.stderr)
-        sys.exit(1)
-    if not trange and (not tbegin or not tend):
-        error_exit('Missing time range')
-    try:
-        d = {}
-        with open(filename, 'r') as f:
-            line = f.readline()
-            dataValid = False
-            while line:
-                if dataValid:
-                    # Ende der Daten
-                    if line.startswith('"[Annotations/User Records'):
-                        dataValid = False
-                    else:
-                        l = line.strip()
-                        a = l.split('\t')# An Tabulatoren trennen
-                        # a[0] = "Time", a[1] = "Scan", a[2] = "Mass 4", a[3] = "Sum Scanned Masses"
-                        if a[0]:
-                            key = a[0].strip('"')
-                            # Timestamp als key für Dictionary
-                            d[key] = a[2]
-                else:
-                    # Beginn der Daten
-                    if line.startswith('"Time"'):
-                        dataValid = True
-                line = f.readline()            
-    except:
-        error_exit("Can't read file: " +  filename)
-    finally:
-        f.close()
-    # Sortieren bei neueren Python-Versionen unnötig?    
-    data = OrderedDict(sorted(d.items()))
-    
-    def doAverage(beg, end):
-        sum = 0.0
-        cnt = 0
-        for key in data:
-            if key >= beg and key < end:
-              #print(key, '-->', data[key])
-              cnt += 1
-              sum += float(data[key])
-        return sum / cnt
-    
-    tb = []
-    te = []
-    res = []
-    
-    if trange:
-        if not isinstance(trange,list):
-            trange = [trange]# Einzelwert zu Array machen
-        for x in trange:
-            a = x.split(' -')
-            tb.append(a[0].strip())
-            te.append(a[1].strip())
-    else:
-        if not isinstance(tbegin,list):
-            tb = [tbegin]# Einzelwert zu Array machen
-        if not isinstance(tend,list):
-            te = [tend]# Einzelwert zu Array machen
-    
-    i = 0
-    while i < len(tb):
-        s = doAverage(tb[i], te[i])
-        res.append(s)
-        i += 1
-    if len(res) == 1:
-        return res[0]# Bei nur einem Wert: kein Array
-    else:
-        return res
-
-trangeArrayTL=list(I_TL_time)
-trangeArrayFM=list(I_FM_time)
-trangeArrayOff=list(I_Offs_time)
-
-xtrangeArray = [
-              '28.07.2022 09:19:19 -28.07.2022 09:21:18 '
-                            
-            ]
-#trangeArray = I_TL_time
-
-x1 = getMassAverage(filename=dateiQMS,trange=trangeArrayTL )
-i = 0
-while i < len(x1):
-    print(i, 'Mass Avarage: ', x1[i])
-    i += 1
-print(x1)
-
-x2 = getMassAverage(filename=dateiQMS,trange=trangeArrayFM )
-i = 0
-while i < len(x2):
-    print(i, 'Mass Avarage: ', x2[i])
-    i += 1
-print(x2)
-
-x3 = getMassAverage(filename=dateiQMS,trange=trangeArrayOff)
-i = 0
-while i < len(x3):
-    print(i, 'Mass Avarage: ', x3[i])
-    i += 1
-print(x3)
-I_TL=np.array(x1)
-I_FM=np.array(x2)
-I_Offs=np.array(x3)
-
-########################################################################################################################################
-
-
-# Temperatur
-lis_T_fm = T_fm.tolist()
-lis_T_room = T_room.tolist()
-lis_T_tl1 = T_tl1.tolist()
-lis_T_tl2 = T_tl2.tolist()
-lis_T_tl3 = T_tl3.tolist()
-lis_T_tl4 = T_tl4.tolist()
-
-
-# Druck
-
-if gauge == 0.01 :
-    lis_p_offs_01 = p_offs_01.tolist()
-    lis_p_fill_01 = p_fill_01.tolist()
-    lis_p_offs_srg = p_offs_srg.tolist()
-    lis_p_fill_srg = p_fill_srg.tolist()
-    
-    
-    
-else:
-    lis_p_offs = p_offs.tolist()
-    lis_p_fill = p_fill.tolist()
-    
-    
-    
-
-
-
-lis_p_ig = p_ig.tolist()
-# I-QMS
-lis_I_TL_time = I_TL_time.tolist()
-lis_I_Offs_time = I_Offs_time.tolist()
-lis_I_FM_time = I_FM_time.tolist()
-# I-QMS
-lis_I_TL = I_TL.tolist()
-lis_I_Offs = I_Offs.tolist()
-lis_I_FM = I_FM.tolist()
-# Datum
-# Datum
-lis_datum = datum.tolist()
-lis_time = time.tolist()
-
-# Ventil
-lis_valve = Valve.tolist()
-
-
-datum_meas = lis_datum[0:1]
-
-
-
-
-if L == 1 :
-    #Leitwert
-    lis_c = L_ar.tolist()
-
-    # Steigung SZ
-    lis_m1 = m1.tolist()
-    lis_m2 = m2.tolist()
-    lis_m3 = m3.tolist()
-    lis_m4 = m4.tolist()
-
-    # Zeitpunkte
-    lis_t1 = t1.tolist()
-    lis_t2 = t2.tolist()
-    lis_t3 = t3.tolist()
-    lis_t4 = t4.tolist()
-
-    # Zeit pro SZ
-    lis_time1 = time1.tolist()
-    lis_time2 = time2.tolist()
-    lis_time3 = time3.tolist()
-
-    # Druck der SZ
-    lis_pmean = pmean.tolist()
-    lis_pmin = pmin.tolist()
-    lis_pmax= pmax.tolist()
-
-    # Druck der SZ
-    lis_h = h.tolist()
-    
-    
-    doc["Calibration"]["Measurement"]["Values"]={"Temperature": [{"Unit": "C","Type": "T-FM ","Comment":"Temperatur T ","Value": lis_T_fm},
-                                                                {"Unit": "C","Type": "T-Room","Comment":"Temperatur T","Value": lis_T_room},
-                                                                {"Unit": "C","Type": "T-TL1 ","Comment":"Temperatur T","Value": lis_T_tl1},
-                                                               {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl2},
-                                                               {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl3},
-                                                               {"Unit": "C","Type": "T-TL3 ","Comment":"Temperatur T","Value": lis_T_tl4}],
-                                                "Pressure": [{"Unit": "Pa","Type": "Offset pressure ","Value":lis_p_offs},
-                                                             {"Unit": "Pa","Type": " pressure mean","Value":lis_p_fill},
-                                                             {"Unit": "bar","Type": "TL1 pressure ","Value":lis_p_ig}],
-                                                "Date": [{"Unit": "year-month-day","Type": "Datum ","Value":lis_datum},
-                                                             {"Unit": "hh:mm:ss","Type": "Messzeit ","Value":lis_time}],
-                                                "Valve": [{"Unit": "1","Type": "Connection", "Comment":"Connection of the leak" ,"Value":lis_valve}],
-                                                "Current": [{"Unit": "mbar","Type": "I-TL","Value": lis_I_TL},
-                                                          {"Unit": "mbar","Type": "I-FM","Value": lis_I_FM}, 
-                                                          {"Unit": "mbar","Type": "I-Offs","Value": lis_I_Offs}],
-                                                                                         
-                                               "CurrentTime": [{"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-TL","Value": lis_I_TL_time},
-                                                          {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-FM","Value": lis_I_FM_time}, 
-                                                         {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-Offs","Value": lis_I_Offs_time}]
-                                               
-                                     }
-    doc["Calibration"]["Measurement"]["Date"]=[{"Type": "measurement","Value": datum_meas}]
-
-    doc["Calibration"]["Measurement"]["Values"]["Conductance"]={"t": [{"Unit": "s","Type": "t1","Comment":"Zeitpunkt t1 des 1.SZ","Value": lis_t1},
-                                                                            {"Unit": "s","Type": "t2","Comment":"Zeitpunkt t2 des 2.SZ","Value": lis_t2}, 
-                                                                            {"Unit": "s","Type": "t3","Comment":"Zeitpunkt t3 des 3.SZ","Value": lis_t3},
-                                                                           {"Unit": "s","Type": "t4","Comment":"Zeitpunkt t4 des 4.SZ","Value": lis_t4}],
-                                                                "time": [{"Unit": "s","Type": "time1","Comment":"Zeit t2-t1 von SZ","Value": lis_time1},
-                                                                       {"Unit": "s","Type": "time2","Comment":"Zeit t3-t2 von SZ","Value": lis_time2}, 
-                                                                      {"Unit": "s","Type": "time3","Comment":"Zeit t4-t3 von SZ","Value": lis_time3}],
-                                                                "m": [{"Unit": "Pa/s","Type": "m1","Comment":"Steigung m1 des 1.SZ","Value": lis_m1},
-                                                                       {"Unit": "Pa/s","Type": "m2","Comment":"Steigung m1 des 2.SZ","Value": lis_m2}, 
-                                                                      {"Unit": "Pa/s","Type": "m3","Comment":"Steigung m1 des 3.SZ","Value": lis_m3},
-                                                                       {"Unit": "Pa/s","Type": "m3","Comment":"Steigung m1 des 4.SZ","Value": lis_m3}],
-                                                               "pressure": [{"Unit": "Pa","Type": "pmean","Comment":"Mittelwert von p","Value": lis_pmean},
-                                                                      {"Unit": "Pa","Type": "pmin","Comment":"p_min des SZ","Value": lis_pmin}, 
-                                                                      {"Unit": "Pa","Type": "pmax","Comment":"p_max des SZ","Value": lis_pmax}],
-                                                               "l": [{"Unit": "mm","Type": "l","Comment":"Hub des Verdrängers","Value": lis_h}],
-                                                               "C": [{"Unit": "m^3/s","Type": "Constanter Leitwert ","Value": lis_c}]
-                                                               
-                                                                }
-
-
-
-    
-    
-    print("Constantes Volumen")
-    
-                               
-                                                                
-else:
-    
-    lis_c = L_ar.tolist()
-    if gauge == 0.01 :
-        doc["Calibration"]["Measurement"]["Values"]={"Temperature": [{"Unit": "C","Type": "T-FM ","Comment":"Temperatur T ","Value": lis_T_fm},
-                                                                    {"Unit": "C","Type": "T-Room","Comment":"Temperatur T","Value": lis_T_room},
-                                                                    {"Unit": "C","Type": "T-TL1 ","Comment":"Temperatur T","Value": lis_T_tl1},
-                                                                   {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl2},
-                                                                   {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl3},
-                                                                   {"Unit": "C","Type": "T-TL3 ","Comment":"Temperatur T","Value": lis_T_tl4}],
-                                                    "Pressure": [{"Unit": "DCR","Type": "Offset pressure SRG","Value":lis_p_offs_srg},
-                                                                 {"Unit": "DCR","Type": "Fill pressure SRG ","Value":lis_p_fill_srg},
-                                                                 {"Unit": "Pa","Type": "Offset pressure 01Torr","Value":lis_p_offs_01},
-                                                                 {"Unit": "Pa","Type": "Fill pressure 01Torr","Value":lis_p_fill_01},
-                                                                 {"Unit": "bar","Type": "TL1 pressure ","Value":lis_p_ig}],
-                                                    "Date": [{"Unit": "year-month-day","Type": "Datum ","Value":lis_datum},
-                                                                 {"Unit": "hh:mm:ss","Type": "Messzeit ","Value":lis_time}],
-                                                    "Valve": [{"Unit": "1","Type": "Connection", "Comment":"Connection of the leak" ,"Value":lis_valve}],
-                                                    "Current": [{"Unit": "mbar","Type": "I-TL","Value": lis_I_TL},
-                                                              {"Unit": "mbar","Type": "I-FM","Value": lis_I_FM}, 
-                                                              {"Unit": "mbar","Type": "I-Offs","Value": lis_I_Offs}],
-                                                                                             
-                                                   "CurrentTime": [{"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-TL","Value": lis_I_TL_time},
-                                                              {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-FM","Value": lis_I_FM_time}, 
-                                                             {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-Offs","Value": lis_I_Offs_time}]
-                                                   }
-        print("SRG")
-        
-    else:
-        doc["Calibration"]["Measurement"]["Values"]={"Temperature": [{"Unit": "C","Type": "T-FM ","Comment":"Temperatur T ","Value": lis_T_fm},
-                                                                    {"Unit": "C","Type": "T-Room","Comment":"Temperatur T","Value": lis_T_room},
-                                                                    {"Unit": "C","Type": "T-TL1 ","Comment":"Temperatur T","Value": lis_T_tl1},
-                                                                   {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl2},
-                                                                   {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl3},
-                                                                   {"Unit": "C","Type": "T-TL3 ","Comment":"Temperatur T","Value": lis_T_tl4}],
-                                                    "Pressure": [{"Unit": "Pa","Type": "Offset pressure ","Value":lis_p_offs},
-                                                                 {"Unit": "Pa","Type": " pressure fill","Value":lis_p_fill},
-                                                                
-                                                                 {"Unit": "bar","Type": "TL1 pressure ","Value":lis_p_ig}],
-                                                    "Date": [{"Unit": "year-month-day","Type": "Datum ","Value":lis_datum},
-                                                                 {"Unit": "hh:mm:ss","Type": "Messzeit ","Value":lis_time}],
-                                                    "Valve": [{"Unit": "1","Type": "Connection", "Comment":"Connection of the leak" ,"Value":lis_valve}],
-                                                    "Current": [{"Unit": "mbar","Type": "I-TL","Value": lis_I_TL},
-                                                              {"Unit": "mbar","Type": "I-FM","Value": lis_I_FM}, 
-                                                              {"Unit": "mbar","Type": "I-Offs","Value": lis_I_Offs}],
-                                                                                             
-                                                   "CurrentTime": [{"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-TL","Value": lis_I_TL_time},
-                                                              {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-FM","Value": lis_I_FM_time}, 
-                                                             {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-Offs","Value": lis_I_Offs_time}]
-                                                   }
-        doc["Calibration"]["Measurement"]["Values"]["Conductance"]={  "C": [{"Unit": "m^3/s","Type": "Constanter Leitwert ","Value": lis_c}]}
-    print("Constanter Leitwert")
-    
-                                                            
-    
-        
-    
-    
-    
-doc["Calibration"]["Measurement"]["Date"]=[{"Type": "measurement","Value": datum_meas}]
-
-
-    
-
-
-
-lis_mass_no = mass_no.tolist()[0]
-lis_mass_value = mass_value.tolist()
-lis_mass_value_offs = mass_value_offs.tolist()[0]
-
-
-
-
-key_value=dict(zip(def_key, def_value))
-key_value_offs=dict(zip(def_key_offs, def_value_offs))
-
-
-
-doc["Calibration"]["Measurement"]["AuxValues"]={"ScanQMS": [{"Unit": "Mass","Type": "QMS ","Comment":"Masse ","Value":lis_mass_no},
-                                                            {"Unit": "mbar","Type": "Current","Comment":"Wert / Masse","Value": lis_mass_value},
-                                                            {"Unit": "mbar","Type": "Current Offset","Comment":"Wert / Masse","Value": lis_mass_value_offs}],
-                                                "DefQMS": [{"Type": "Scan QMS ","Value":key_value},
-                                                           {"Type": "Scan Offset QMS","Value": key_value_offs}]}
-
-
-#doc["Calibration"]["Measurement"]["AuxValues"]={"ScanQMS": [{"Unit": "Mass","Type": "QMS ","Comment":"Masse ","Value":lis_mass_no},
-#                                                            {"Unit": "mbar","Type": "Current","Comment":"Wert / Masse","Value": lis_mass_value},
-##                                                            {"Unit": "mbar","Type": "Current Offset","Comment":"Wert / Masse","Value": lis_mass_value_offs}],
-#                                                "DefQMS": [{"Type": "Scan QMS ","Value":key_value},
-#                                                           {"Type": "Scan Offset QMS","Value": key_value_offs}]}
-
-db.save(doc)
-
-content=pathlib.Path('Scan.pdf').read_bytes() 
-
-db.put_attachment(doc, content, "Scan.pdf" , content_type="'application/pdf")
-
-
-
-
diff --git a/file-to-couchdb_tl1.py b/file-to-couchdb_tl1.py
new file mode 100644
index 0000000000000000000000000000000000000000..402093275779a4bb27854aed99b95063110f1cdd
--- /dev/null
+++ b/file-to-couchdb_tl1.py
@@ -0,0 +1,1360 @@
+<<<<<<<< HEAD:file-to-couchdb_TLV_cL.py
+# -*- coding: utf-8 -*-
+"""
+Created on Fri Jul  1 12:12:37 2022
+
+@author: becker07
+"""
+import sys
+import numpy as np
+import couchdb 
+import pandas as pd
+import json
+import csv
+import re
+from matplotlib import pyplot as plt
+import pathlib
+
+couch = couchdb.Server('http://a73434.berlin.ptb.de:5984')
+db = couch['vl_db'] # existing
+
+
+## Eingabe von:
+#    - Kalibrierscheinnummer
+#    - Jahr der Kalibrierung 
+#    - laufende Nummer der Kalibrierung
+
+
+
+cal_cert = "75573"
+year = "2024"
+no = "0001"
+QMS="ja"   ######### ja beim Scan
+kk_ik_pn= "kk" ######## kk,ik oder pn
+
+
+
+json_file = "cal-" + year + "-fm1-kk-" + cal_cert + "_" + no
+doc = db.get(json_file) 
+print(json_file)
+
+
+dateiTab = cal_cert 
+#print(dateiTab)
+
+
+dateiTab=pd.read_csv(dateiTab,  sep="\t", decimal = ',' )
+
+L_ar=dateiTab["L"]
+print('Leitwert j= 1, nein = 0 :: ', L_ar)
+
+L=L_ar[0]
+print('Leitwer : ',L)
+
+
+gauge = float(doc["Calibration"]["CustomerObject"]["Setup"]["CDG"])
+print(gauge)
+
+fileQMS = "QMS" +  cal_cert + ".txt" 
+dateiQMS =fileQMS
+ScanQMS="Scan"+cal_cert + ".txt"
+ScanOffsQMS="Scan_Offs"+cal_cert + ".txt"
+print(ScanQMS)
+
+# Die Daten aus dem File mit der entsprechenden Kalibrierscheinnummer werden eingelesen:
+# datum, time, p_up und alle Temperaturen, 
+
+
+#datei = "N:\Abt_7\Fb75\Vakuum\Messplaetze\TL1\Kalibrierungen\\22\\TP7464.txt"
+
+if L == 1 :
+    
+    
+    m1=dateiTab["m1"]
+    m2=dateiTab["m2"]
+    m3=dateiTab["m3"]
+    m4=dateiTab["m4"]
+
+    t1=dateiTab["t1"]
+    t2=dateiTab["t2"]
+    t3=dateiTab["t3"]
+    t4=dateiTab["t4"]
+    time1=dateiTab["time1"]
+    time2=dateiTab["time2"]
+    time3=dateiTab["time3"]
+
+    pmean=dateiTab["p-mean"]*100
+    pmin=dateiTab["p-min"]*100
+    pmax=dateiTab["p-max"]*100
+    
+
+    h=dateiTab["distance"]
+    
+       
+    print("Constantes Volumen",h)
+    
+                               
+                                                                
+else:
+    print("Constanter Leitwert")
+
+
+datum=dateiTab["Datum"]
+time=dateiTab["Zeit"]
+gas=dateiTab["Gasart"]
+
+if gauge== 0.01 :
+    p_offs_01=dateiTab["p-offset"]*100
+    p_fill_01=dateiTab["p-fill "]*100
+    p_fill_srg=dateiTab["p-max"]
+    p_offs_srg=dateiTab["p-min"]
+    
+else :
+    p_offs=dateiTab["p-offset"]*100
+    p_fill=dateiTab["p-fill "]*100
+#p_fill=np.genfromtxt(dateiTab,skip_header=1,delimiter='\t',usecols=(5))
+
+p_ig=dateiTab["Kommentar"]
+T_room=dateiTab["T-Raum"]
+T_fm=dateiTab["T-FM"]
+T_tl1=dateiTab["T-TL1"]
+T_tl2=dateiTab["T-TL2"]
+T_tl3=dateiTab["T-TL3"]
+T_tl4=dateiTab["T-TL4"]
+
+#print(T_fm,T_room,T_tl1, T_tl2,T_tl3,T_tl4)
+
+
+I_TL_time=dateiTab["Time-TL"]
+I_Offs_time=dateiTab["Time-offset"]
+I_FM_time=dateiTab["Time-FM"]
+
+#print(I_TL_time,I_Offs_time,I_FM_time)
+
+Valve=dateiTab["Ventil"]
+
+
+if QMS == "ja" :
+    I_TL_time=dateiTab["Time-TL"]
+    I_Offs_time=dateiTab["Time-offset"]
+    I_FM_time=dateiTab["Time-FM"]
+
+    #print(I_TL_time,I_Offs_time,I_FM_time)
+
+
+####################### Der Scan des QMS ##############################################################################
+
+
+
+##############  die leeren Zeilen und Überschriften werden gelöscht  ###################
+
+    with open(ScanQMS, "r") as fp:
+        tab=fp.read()
+
+    with open('ScanQMS.txt', 'w') as fp:
+        fp.write(tab) 
+        
+    with open(ScanOffsQMS, "r") as fp:
+        tab=fp.read()
+
+    with open('ScanOffsQMS.txt', 'w') as fp:
+        fp.write(tab)
+
+
+    del_def = []
+    with open('ScanQMS.txt', "r") as fp:
+        del_def = fp.readlines()
+        with open('ScanQMS.txt', "w") as fp:
+            for number, line in enumerate(del_def):
+                if number not in [0, 1,6,7,22,23,24,25,47,48]:
+                    fp.write(line)
+            
+            del_def = []
+            with open('ScanOffsQMS.txt', "r") as fp:
+                del_def = fp.readlines()
+                with open('ScanOffsQMS.txt', "w") as fp:
+                    for number, line in enumerate(del_def):
+                        if number not in [0, 1,6,7,22,23,24,25,47,48]:
+                            fp.write(line)
+
+
+
+
+###########  Scan #####################
+
+    with open('ScanQMS.txt','r') as file:
+        tab=file.read()
+        lstdef=tab.rfind("Channel count")+16
+        lsttab=tab.rfind("Scan Data (Pressures in mbar)")+32
+        filetab=tab[lsttab:]                                       ### Das File wird getrennt und die Tabelle mit den Messwerten in das filetab übergeben
+        filedef=tab[:lstdef]                                       ### Das File wird getrennt und die Einstellungen und Infos in filedef übergeben
+    
+    
+    with open('QMS-Def.txt', 'w') as f:
+        f.write(filedef)
+    
+    
+    df_tab = pd.read_csv("QMS-Def.txt",
+                         sep="\t",
+                         #usecols=["Time"]
+                         header=None,
+                         )
+
+    def_key=np.array(df_tab[0])
+    l=len(def_key)
+    print(l)
+    #def_key=np.delete(def_key, l-1)
+    def_value=np.array(df_tab[1], dtype=str)
+    #def_value=np.delete(def_value, l-1)
+    
+
+   
+    with open('QMS-Scan.txt', 'w') as f:
+        f.write(filetab)    
+        df = pd.read_csv("QMS-Scan.txt",
+                         sep="\t",
+                         #usecols=["Time"]
+                         header=None,
+                         )
+        df=df.replace(np.nan, 0)
+
+
+    l=len(df)
+
+    print(l)
+
+    mass_no=np.array(df[0:1])
+    mass_unit=mass_no[0]
+    
+    
+   
+
+    if l == 3:
+        mass_value=np.array(df[1:2])
+        mass_value=mass_value[0]
+        print(mass_value())
+    else:
+        mass_value=np.array(df[l-2:l-1])
+        mass_value=mass_value[0]
+        
+
+    
+#############################################################################################################
+###########  Scan Offset   #####################
+
+    with open('ScanOffsQMS.txt','r') as file:
+        tab_offs=file.read()
+        lstdef_offs=tab_offs.rfind("Channel count")+16
+        lsttab_offs=tab_offs.rfind("Scan Data (Pressures in mbar)")+32
+        filetab_offs=tab_offs[lsttab_offs:]                                       ### Das File wird getrennt und die Tabelle mit den Messwerten in das filetab übergeben
+        filedef_offs=tab_offs[:lstdef_offs]                                       ### Das File wird getrennt und die Einstellungen und Infos in filedef übergeben
+    
+    
+    with open('QMS_Offs-Def.txt', 'w') as f:
+        f.write(filedef_offs)
+    
+    
+    df_tab_offs = pd.read_csv("QMS_Offs-Def.txt",
+                         sep="\t",
+                         #usecols=["Time"]
+                         header=None,
+                         )
+
+    def_key_offs=np.array(df_tab_offs[0])
+    l=len(def_key_offs)
+    def_value_offs=np.array(df_tab_offs[1], dtype=str)
+    #def_value=np.delete(def_value, l-1)
+    
+
+   
+    with open('QMS_Offs-Scan.txt', 'w') as f:
+        f.write(filetab_offs)    
+        df_offs = pd.read_csv("QMS_Offs-Scan.txt",
+                         sep="\t",
+                         #usecols=["Time"]
+                         header=None,
+                         )
+        df_offs=df_offs.replace(np.nan, 0)
+
+
+    l=len(df_offs)
+
+    print(l)
+
+       
+
+    if l == 3:
+        mass_value_offs=np.array(df_offs[1:2])
+        mass_value_off=mass_value_offs[0]
+        print(mass_value_offs())
+    else:
+        mass_value_offs=np.array(df_offs[l-2:l-1])
+        mass_value_off=mass_value_offs[0]
+    
+
+#############################################################################################################
+
+###################### Plot der Scans werden abgebildet und den json-dokument hinzugefügt #####################
+I_Scan=np.float64(mass_value[2:-2])
+I_Scan_Offs=np.float64(mass_value_off[2:-2])
+Mass_Scan=mass_no[0]
+Mass_Scan=Mass_Scan[2:-2]
+
+for i in range(len(Mass_Scan)):
+    Mass_Scan[i] = re.sub(r"Mass ", "", Mass_Scan[i]).strip()
+   
+   
+Mass_Scan=np.float64(Mass_Scan)
+
+fig=plt.figure()
+ax=fig.add_axes([0,0,4,2])
+ax.set_xlabel('Masse')
+ax.set_ylabel('QMS-Signal')
+ax.set_yscale('log')
+#plt.plot(1010,4.65e-10, 'bo')
+plt.plot(Mass_Scan,I_Scan, label=r'Floww')
+plt.plot(Mass_Scan,I_Scan_Offs,label=r'Offset' )
+plt.legend()
+
+
+plt.grid()
+
+fig.savefig("Scan.pdf", bbox_inches='tight')
+
+
+
+#############################################################################################################
+
+from collections import OrderedDict
+
+def getMassAverage(filename, tbegin = None, tend = None, trange = None):
+    def error_exit(x):
+        print('ERROR: ', str(x), file=sys.stderr)
+        sys.exit(1)
+    if not trange and (not tbegin or not tend):
+        error_exit('Missing time range')
+    try:
+        d = {}
+        with open(filename, 'r') as f:
+            line = f.readline()
+            dataValid = False
+            while line:
+                if dataValid:
+                    # Ende der Daten
+                    if line.startswith('"[Annotations/User Records'):
+                        dataValid = False
+                    else:
+                        l = line.strip()
+                        a = l.split('\t')# An Tabulatoren trennen
+                        # a[0] = "Time", a[1] = "Scan", a[2] = "Mass 4", a[3] = "Sum Scanned Masses"
+                        if a[0]:
+                            key = a[0].strip('"')
+                            # Timestamp als key für Dictionary
+                            d[key] = a[2]
+                else:
+                    # Beginn der Daten
+                    if line.startswith('"Time"'):
+                        dataValid = True
+                line = f.readline()            
+    except:
+        error_exit("Can't read file: " +  filename)
+    finally:
+        f.close()
+    # Sortieren bei neueren Python-Versionen unnötig?    
+    data = OrderedDict(sorted(d.items()))
+    
+    def doAverage(beg, end):
+        sum = 0.0
+        cnt = 0
+        for key in data:
+            if key >= beg and key < end:
+              #print(key, '-->', data[key])
+              cnt += 1
+              sum += float(data[key])
+        return sum / cnt
+    
+    tb = []
+    te = []
+    res = []
+    
+    if trange:
+        if not isinstance(trange,list):
+            trange = [trange]# Einzelwert zu Array machen
+        for x in trange:
+            a = x.split(' -')
+            tb.append(a[0].strip())
+            te.append(a[1].strip())
+    else:
+        if not isinstance(tbegin,list):
+            tb = [tbegin]# Einzelwert zu Array machen
+        if not isinstance(tend,list):
+            te = [tend]# Einzelwert zu Array machen
+    
+    i = 0
+    while i < len(tb):
+        s = doAverage(tb[i], te[i])
+        res.append(s)
+        i += 1
+    if len(res) == 1:
+        return res[0]# Bei nur einem Wert: kein Array
+    else:
+        return res
+
+trangeArrayTL=list(I_TL_time)
+trangeArrayFM=list(I_FM_time)
+trangeArrayOff=list(I_Offs_time)
+
+xtrangeArray = [
+              '28.07.2022 09:19:19 -28.07.2022 09:21:18 '
+                            
+            ]
+#trangeArray = I_TL_time
+
+x1 = getMassAverage(filename=dateiQMS,trange=trangeArrayTL )
+i = 0
+while i < len(x1):
+    print(i, 'Mass Avarage: ', x1[i])
+    i += 1
+print(x1)
+
+x2 = getMassAverage(filename=dateiQMS,trange=trangeArrayFM )
+i = 0
+while i < len(x2):
+    print(i, 'Mass Avarage: ', x2[i])
+    i += 1
+print(x2)
+
+x3 = getMassAverage(filename=dateiQMS,trange=trangeArrayOff)
+i = 0
+while i < len(x3):
+    print(i, 'Mass Avarage: ', x3[i])
+    i += 1
+print(x3)
+I_TL=np.array(x1)
+I_FM=np.array(x2)
+I_Offs=np.array(x3)
+
+########################################################################################################################################
+
+
+# Temperatur
+lis_T_fm = T_fm.tolist()
+lis_T_room = T_room.tolist()
+lis_T_tl1 = T_tl1.tolist()
+lis_T_tl2 = T_tl2.tolist()
+lis_T_tl3 = T_tl3.tolist()
+lis_T_tl4 = T_tl4.tolist()
+
+
+# Druck
+
+if gauge == 0.01 :
+    lis_p_offs_01 = p_offs_01.tolist()
+    lis_p_fill_01 = p_fill_01.tolist()
+    lis_p_offs_srg = p_offs_srg.tolist()
+    lis_p_fill_srg = p_fill_srg.tolist()
+    
+    
+    
+else:
+    lis_p_offs = p_offs.tolist()
+    lis_p_fill = p_fill.tolist()
+    
+    
+    
+
+
+
+lis_p_ig = p_ig.tolist()
+# I-QMS
+lis_I_TL_time = I_TL_time.tolist()
+lis_I_Offs_time = I_Offs_time.tolist()
+lis_I_FM_time = I_FM_time.tolist()
+# I-QMS
+lis_I_TL = I_TL.tolist()
+lis_I_Offs = I_Offs.tolist()
+lis_I_FM = I_FM.tolist()
+# Datum
+# Datum
+lis_datum = datum.tolist()
+lis_time = time.tolist()
+
+# Ventil
+lis_valve = Valve.tolist()
+
+
+datum_meas = lis_datum[0:1]
+
+
+
+
+if L == 1 :
+    #Leitwert
+    lis_c = L_ar.tolist()
+
+    # Steigung SZ
+    lis_m1 = m1.tolist()
+    lis_m2 = m2.tolist()
+    lis_m3 = m3.tolist()
+    lis_m4 = m4.tolist()
+
+    # Zeitpunkte
+    lis_t1 = t1.tolist()
+    lis_t2 = t2.tolist()
+    lis_t3 = t3.tolist()
+    lis_t4 = t4.tolist()
+
+    # Zeit pro SZ
+    lis_time1 = time1.tolist()
+    lis_time2 = time2.tolist()
+    lis_time3 = time3.tolist()
+
+    # Druck der SZ
+    lis_pmean = pmean.tolist()
+    lis_pmin = pmin.tolist()
+    lis_pmax= pmax.tolist()
+
+    # Druck der SZ
+    lis_h = h.tolist()
+    
+    
+    doc["Calibration"]["Measurement"]["Values"]={"Temperature": [{"Unit": "C","Type": "T-FM ","Comment":"Temperatur T ","Value": lis_T_fm},
+                                                                {"Unit": "C","Type": "T-Room","Comment":"Temperatur T","Value": lis_T_room},
+                                                                {"Unit": "C","Type": "T-TL1 ","Comment":"Temperatur T","Value": lis_T_tl1},
+                                                               {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl2},
+                                                               {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl3},
+                                                               {"Unit": "C","Type": "T-TL3 ","Comment":"Temperatur T","Value": lis_T_tl4}],
+                                                "Pressure": [{"Unit": "Pa","Type": "Offset pressure ","Value":lis_p_offs},
+                                                             {"Unit": "Pa","Type": " pressure mean","Value":lis_p_fill},
+                                                             {"Unit": "bar","Type": "TL1 pressure ","Value":lis_p_ig}],
+                                                "Date": [{"Unit": "year-month-day","Type": "Datum ","Value":lis_datum},
+                                                             {"Unit": "hh:mm:ss","Type": "Messzeit ","Value":lis_time}],
+                                                "Valve": [{"Unit": "1","Type": "Connection", "Comment":"Connection of the leak" ,"Value":lis_valve}],
+                                                "Current": [{"Unit": "mbar","Type": "I-TL","Value": lis_I_TL},
+                                                          {"Unit": "mbar","Type": "I-FM","Value": lis_I_FM}, 
+                                                          {"Unit": "mbar","Type": "I-Offs","Value": lis_I_Offs}],
+                                                                                         
+                                               "CurrentTime": [{"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-TL","Value": lis_I_TL_time},
+                                                          {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-FM","Value": lis_I_FM_time}, 
+                                                         {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-Offs","Value": lis_I_Offs_time}]
+                                               
+                                     }
+    doc["Calibration"]["Measurement"]["Date"]=[{"Type": "measurement","Value": datum_meas}]
+
+    doc["Calibration"]["Measurement"]["Values"]["Conductance"]={"t": [{"Unit": "s","Type": "t1","Comment":"Zeitpunkt t1 des 1.SZ","Value": lis_t1},
+                                                                            {"Unit": "s","Type": "t2","Comment":"Zeitpunkt t2 des 2.SZ","Value": lis_t2}, 
+                                                                            {"Unit": "s","Type": "t3","Comment":"Zeitpunkt t3 des 3.SZ","Value": lis_t3},
+                                                                           {"Unit": "s","Type": "t4","Comment":"Zeitpunkt t4 des 4.SZ","Value": lis_t4}],
+                                                                "time": [{"Unit": "s","Type": "time1","Comment":"Zeit t2-t1 von SZ","Value": lis_time1},
+                                                                       {"Unit": "s","Type": "time2","Comment":"Zeit t3-t2 von SZ","Value": lis_time2}, 
+                                                                      {"Unit": "s","Type": "time3","Comment":"Zeit t4-t3 von SZ","Value": lis_time3}],
+                                                                "m": [{"Unit": "Pa/s","Type": "m1","Comment":"Steigung m1 des 1.SZ","Value": lis_m1},
+                                                                       {"Unit": "Pa/s","Type": "m2","Comment":"Steigung m1 des 2.SZ","Value": lis_m2}, 
+                                                                      {"Unit": "Pa/s","Type": "m3","Comment":"Steigung m1 des 3.SZ","Value": lis_m3},
+                                                                       {"Unit": "Pa/s","Type": "m3","Comment":"Steigung m1 des 4.SZ","Value": lis_m3}],
+                                                               "pressure": [{"Unit": "Pa","Type": "pmean","Comment":"Mittelwert von p","Value": lis_pmean},
+                                                                      {"Unit": "Pa","Type": "pmin","Comment":"p_min des SZ","Value": lis_pmin}, 
+                                                                      {"Unit": "Pa","Type": "pmax","Comment":"p_max des SZ","Value": lis_pmax}],
+                                                               "l": [{"Unit": "mm","Type": "l","Comment":"Hub des Verdrängers","Value": lis_h}],
+                                                               "C": [{"Unit": "m^3/s","Type": "Constanter Leitwert ","Value": lis_c}]
+                                                               
+                                                                }
+
+
+
+    
+    
+    print("Constantes Volumen")
+    
+                               
+                                                                
+else:
+    
+    lis_c = L_ar.tolist()
+    if gauge == 0.01 :
+        doc["Calibration"]["Measurement"]["Values"]={"Temperature": [{"Unit": "C","Type": "T-FM ","Comment":"Temperatur T ","Value": lis_T_fm},
+                                                                    {"Unit": "C","Type": "T-Room","Comment":"Temperatur T","Value": lis_T_room},
+                                                                    {"Unit": "C","Type": "T-TL1 ","Comment":"Temperatur T","Value": lis_T_tl1},
+                                                                   {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl2},
+                                                                   {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl3},
+                                                                   {"Unit": "C","Type": "T-TL3 ","Comment":"Temperatur T","Value": lis_T_tl4}],
+                                                    "Pressure": [{"Unit": "DCR","Type": "Offset pressure SRG","Value":lis_p_offs_srg},
+                                                                 {"Unit": "DCR","Type": "Fill pressure SRG ","Value":lis_p_fill_srg},
+                                                                 {"Unit": "Pa","Type": "Offset pressure 01Torr","Value":lis_p_offs_01},
+                                                                 {"Unit": "Pa","Type": "Fill pressure 01Torr","Value":lis_p_fill_01},
+                                                                 {"Unit": "bar","Type": "TL1 pressure ","Value":lis_p_ig}],
+                                                    "Date": [{"Unit": "year-month-day","Type": "Datum ","Value":lis_datum},
+                                                                 {"Unit": "hh:mm:ss","Type": "Messzeit ","Value":lis_time}],
+                                                    "Valve": [{"Unit": "1","Type": "Connection", "Comment":"Connection of the leak" ,"Value":lis_valve}],
+                                                    "Current": [{"Unit": "mbar","Type": "I-TL","Value": lis_I_TL},
+                                                              {"Unit": "mbar","Type": "I-FM","Value": lis_I_FM}, 
+                                                              {"Unit": "mbar","Type": "I-Offs","Value": lis_I_Offs}],
+                                                                                             
+                                                   "CurrentTime": [{"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-TL","Value": lis_I_TL_time},
+                                                              {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-FM","Value": lis_I_FM_time}, 
+                                                             {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-Offs","Value": lis_I_Offs_time}]
+                                                   }
+        print("SRG")
+        
+    else:
+        doc["Calibration"]["Measurement"]["Values"]={"Temperature": [{"Unit": "C","Type": "T-FM ","Comment":"Temperatur T ","Value": lis_T_fm},
+                                                                    {"Unit": "C","Type": "T-Room","Comment":"Temperatur T","Value": lis_T_room},
+                                                                    {"Unit": "C","Type": "T-TL1 ","Comment":"Temperatur T","Value": lis_T_tl1},
+                                                                   {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl2},
+                                                                   {"Unit": "C","Type": "T-TL2 ","Comment":"Temperatur T","Value":lis_T_tl3},
+                                                                   {"Unit": "C","Type": "T-TL3 ","Comment":"Temperatur T","Value": lis_T_tl4}],
+                                                    "Pressure": [{"Unit": "Pa","Type": "Offset pressure ","Value":lis_p_offs},
+                                                                 {"Unit": "Pa","Type": " pressure fill","Value":lis_p_fill},
+                                                                
+                                                                 {"Unit": "bar","Type": "TL1 pressure ","Value":lis_p_ig}],
+                                                    "Date": [{"Unit": "year-month-day","Type": "Datum ","Value":lis_datum},
+                                                                 {"Unit": "hh:mm:ss","Type": "Messzeit ","Value":lis_time}],
+                                                    "Valve": [{"Unit": "1","Type": "Connection", "Comment":"Connection of the leak" ,"Value":lis_valve}],
+                                                    "Current": [{"Unit": "mbar","Type": "I-TL","Value": lis_I_TL},
+                                                              {"Unit": "mbar","Type": "I-FM","Value": lis_I_FM}, 
+                                                              {"Unit": "mbar","Type": "I-Offs","Value": lis_I_Offs}],
+                                                                                             
+                                                   "CurrentTime": [{"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-TL","Value": lis_I_TL_time},
+                                                              {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-FM","Value": lis_I_FM_time}, 
+                                                             {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-Offs","Value": lis_I_Offs_time}]
+                                                   }
+        doc["Calibration"]["Measurement"]["Values"]["Conductance"]={  "C": [{"Unit": "m^3/s","Type": "Constanter Leitwert ","Value": lis_c}]}
+    print("Constanter Leitwert")
+    
+                                                            
+    
+        
+    
+    
+    
+doc["Calibration"]["Measurement"]["Date"]=[{"Type": "measurement","Value": datum_meas}]
+
+
+    
+
+
+
+lis_mass_no = mass_no.tolist()[0]
+lis_mass_value = mass_value.tolist()
+lis_mass_value_offs = mass_value_offs.tolist()[0]
+
+
+
+
+key_value=dict(zip(def_key, def_value))
+key_value_offs=dict(zip(def_key_offs, def_value_offs))
+
+
+
+doc["Calibration"]["Measurement"]["AuxValues"]={"ScanQMS": [{"Unit": "Mass","Type": "QMS ","Comment":"Masse ","Value":lis_mass_no},
+                                                            {"Unit": "mbar","Type": "Current","Comment":"Wert / Masse","Value": lis_mass_value},
+                                                            {"Unit": "mbar","Type": "Current Offset","Comment":"Wert / Masse","Value": lis_mass_value_offs}],
+                                                "DefQMS": [{"Type": "Scan QMS ","Value":key_value},
+                                                           {"Type": "Scan Offset QMS","Value": key_value_offs}]}
+
+
+#doc["Calibration"]["Measurement"]["AuxValues"]={"ScanQMS": [{"Unit": "Mass","Type": "QMS ","Comment":"Masse ","Value":lis_mass_no},
+#                                                            {"Unit": "mbar","Type": "Current","Comment":"Wert / Masse","Value": lis_mass_value},
+##                                                            {"Unit": "mbar","Type": "Current Offset","Comment":"Wert / Masse","Value": lis_mass_value_offs}],
+#                                                "DefQMS": [{"Type": "Scan QMS ","Value":key_value},
+#                                                           {"Type": "Scan Offset QMS","Value": key_value_offs}]}
+
+db.save(doc)
+
+content=pathlib.Path('Scan.pdf').read_bytes() 
+
+db.put_attachment(doc, content, "Scan.pdf" , content_type="'application/pdf")
+
+
+
+
+========
+# -*- coding: utf-8 -*-
+"""
+Created on Fri Jul  1 12:12:37 2022
+
+@author: becker07
+"""
+import sys
+import numpy as np
+import couchdb 
+import pandas as pd
+import json
+import csv
+import re
+from matplotlib import pyplot as plt
+import pathlib
+
+try:
+    from configparser import ConfigParser
+except ImportError:
+    from ConfigParser import ConfigParser  # ver. < 3.0
+
+
+configtl = ConfigParser()
+ini_values = ConfigParser()
+# parse existing file
+configtl.read('tl.ini')
+ini_values.read('inputs.ini')
+
+server=configtl.get('couch', 'couch')
+db_vl=configtl.get('couch', 'db')
+
+couch = couchdb.Server(server)
+db = couch[db_vl] # existing
+
+
+## Eingabe von:
+#    - Kalibrierscheinnummer
+#    - Jahr der Kalibrierung 
+#    - laufende Nummer der Kalibrierung
+
+path=configtl.get('path', 'path_files')
+
+
+
+cal_cert = ini_values.get('input_cer', 'cal_cert')
+year = ini_values.get('input_gen', 'year')
+no = ini_values.get('input_gen', 'no')
+QMS="ja"   ######### ja beim Scan
+kk_ik_pn= "kk" ######## kk,ik oder pn
+
+
+
+json_file = "cal-" + year + "-fm1-kk-" + cal_cert + "_" + no
+doc = db.get(json_file) 
+print(json_file)
+
+#path='C:\\Users\\becker07\\python\\TL1\\'
+
+dateiTab =  path + cal_cert + "_" + no
+#dateiTab='C:\\Users\\becker07\\python\\TL1\\75561'
+print(dateiTab)
+
+
+dateiTab=pd.read_csv(dateiTab,  sep="\t", decimal = ',' )
+
+L_ar=dateiTab["C "]
+print('Leitwert j= 1, nein = 0 :: ', L_ar)
+
+L=L_ar[0]
+print('Leitwert : ',L)
+
+
+gauge = float(doc["Calibration"]["CustomerObject"]["Setup"]["CDG"])
+print(gauge)
+
+fileQMS = path + "QMS" +  cal_cert + "_" + no + ".txt" 
+dateiQMS =fileQMS
+ScanQMS= path + "Scan"+ cal_cert + "_" + no+ ".txt"
+ScanOffsQMS= path + "ScanOffs"+cal_cert + "_" + no+ ".txt"
+print(ScanQMS)
+
+# Die Daten aus dem File mit der entsprechenden Kalibrierscheinnummer werden eingelesen:
+# datum, time, p_up und alle Temperaturen, 
+
+
+#datei = "N:\Abt_7\Fb75\Vakuum\Messplaetze\TL1\Kalibrierungen\\22\\TP7464.txt"
+
+if L == 1 :
+    
+    
+    m1=dateiTab["m1"]
+    m2=dateiTab["m2"]
+    m3=dateiTab["m3"]
+    m4=dateiTab["m4"]
+
+    t1=dateiTab["t1"]
+    t2=dateiTab["t2"]
+    t3=dateiTab["t3"]
+    t4=dateiTab["t4"]
+    time1=dateiTab["time1"]
+    time2=dateiTab["time2"]
+    time3=dateiTab["time3"]
+
+    pmean=dateiTab["p-mean"]*100
+    pmin=dateiTab["p-min"]*100
+    pmax=dateiTab["p-max"]*100
+    
+
+    h=dateiTab["distance"]
+    
+       
+    print("Constantes Volumen",h)
+    
+                               
+                                                                
+else:
+    print("Constanter Leitwert")
+
+
+datum=dateiTab["Datum"]
+time=dateiTab["Zeit"]
+gas=dateiTab["Gasart"]
+
+if gauge== 0.01 :
+    p_offs_01=dateiTab["p-offset"]*100
+    p_fill_01=dateiTab["p-fill "]*100
+    p_fill_srg=dateiTab["p-max"]
+    p_offs_srg=dateiTab["p-min"]
+    
+else :
+    p_offs=dateiTab["p-offset"]*100
+    p_fill=dateiTab["p-fill "]*100
+#p_fill=np.genfromtxt(dateiTab,skip_header=1,delimiter='\t',usecols=(5))
+
+p_ig=dateiTab["Kommentar"]
+T_room=dateiTab["T-Raum"]
+T_fm=dateiTab["T-FM"]
+T_tl1=dateiTab["T-TL1"]
+T_tl2=dateiTab["T-TL2"]
+T_tl3=dateiTab["T-TL3"]
+T_tl4=dateiTab["T-TL4"]
+
+#print(T_fm,T_room,T_tl1, T_tl2,T_tl3,T_tl4)
+
+
+I_TL_time=dateiTab["Time-TL"]
+I_Offs_time=dateiTab["Time-offset"]
+I_FM_time=dateiTab["Time-FM"]
+
+#print(I_TL_time,I_Offs_time,I_FM_time)
+
+Valve=dateiTab["Ventil"]
+
+
+if QMS == "ja" :
+    I_TL_time=dateiTab["Time-TL"]
+    I_Offs_time=dateiTab["Time-offset"]
+    I_FM_time=dateiTab["Time-FM"]
+
+    #print(I_TL_time,I_Offs_time,I_FM_time)
+
+
+####################### Der Scan des QMS ##############################################################################
+
+
+
+##############  die leeren Zeilen und Überschriften werden gelöscht  ###################
+
+    with open(ScanQMS, "r") as fp:
+        tab=fp.read()
+
+    with open('ScanQMS.txt', 'w') as fp:
+        fp.write(tab) 
+        
+    with open(ScanOffsQMS, "r") as fp:
+        tab=fp.read()
+
+    with open('ScanOffsQMS.txt', 'w') as fp:
+        fp.write(tab)
+
+
+    del_def = []
+    with open('ScanQMS.txt', "r") as fp:
+        del_def = fp.readlines()
+        with open('ScanQMS.txt', "w") as fp:
+            for number, line in enumerate(del_def):
+                if number not in [0, 1,6,7,22,23,24,25,47,48]:
+                    fp.write(line)
+            
+            del_def = []
+            with open('ScanOffsQMS.txt', "r") as fp:
+                del_def = fp.readlines()
+                with open('ScanOffsQMS.txt', "w") as fp:
+                    for number, line in enumerate(del_def):
+                        if number not in [0, 1,6,7,22,23,24,25,47,48]:
+                            fp.write(line)
+
+
+
+
+###########  Scan #####################
+
+    with open('ScanQMS.txt','r') as file:
+        tab=file.read()
+        lstdef=tab.rfind("Channel count")+16
+        lsttab=tab.rfind("Scan Data (Pressures in mbar)")+32
+        filetab=tab[lsttab:]                                       ### Das File wird getrennt und die Tabelle mit den Messwerten in das filetab übergeben
+        filedef=tab[:lstdef]                                       ### Das File wird getrennt und die Einstellungen und Infos in filedef übergeben
+    
+    
+    with open('QMS-Def.txt', 'w') as f:
+        f.write(filedef)
+    
+    
+    df_tab = pd.read_csv("QMS-Def.txt",
+                         sep="\t",
+                         #usecols=["Time"]
+                         header=None,
+                         )
+
+    def_key=np.array(df_tab[0])
+    l=len(def_key)
+    print(l)
+    #def_key=np.delete(def_key, l-1)
+    def_value=np.array(df_tab[1], dtype=str)
+    #def_value=np.delete(def_value, l-1)
+    
+
+   
+    with open('QMS-Scan.txt', 'w') as f:
+        f.write(filetab)    
+        df = pd.read_csv("QMS-Scan.txt",
+                         sep="\t",
+                         #usecols=["Time"]
+                         header=None,
+                         )
+        df=df.replace(np.nan, 0)
+
+
+    l=len(df)
+
+    print(l)
+
+    mass_no=np.array(df[0:1])
+    mass_unit=mass_no[0]
+    
+    
+   
+
+    if l == 3:
+        mass_value=np.array(df[1:2])
+        mass_value=mass_value[0]
+        print(mass_value())
+    else:
+        mass_value=np.array(df[l-2:l-1])
+        mass_value=mass_value[0]
+        
+
+    
+#############################################################################################################
+###########  Scan Offset   #####################
+
+    with open('ScanOffsQMS.txt','r') as file:
+        tab_offs=file.read()
+        lstdef_offs=tab_offs.rfind("Channel count")+16
+        lsttab_offs=tab_offs.rfind("Scan Data (Pressures in mbar)")+32
+        filetab_offs=tab_offs[lsttab_offs:]                                       ### Das File wird getrennt und die Tabelle mit den Messwerten in das filetab übergeben
+        filedef_offs=tab_offs[:lstdef_offs]                                       ### Das File wird getrennt und die Einstellungen und Infos in filedef übergeben
+    
+    
+    with open('QMS_Offs-Def.txt', 'w') as f:
+        f.write(filedef_offs)
+    
+    
+    df_tab_offs = pd.read_csv("QMS_Offs-Def.txt",
+                         sep="\t",
+                         #usecols=["Time"]
+                         header=None,
+                         )
+
+    def_key_offs=np.array(df_tab_offs[0])
+    l=len(def_key_offs)
+    def_value_offs=np.array(df_tab_offs[1], dtype=str)
+    #def_value=np.delete(def_value, l-1)
+    
+
+   
+    with open('QMS_Offs-Scan.txt', 'w') as f:
+        f.write(filetab_offs)    
+        df_offs = pd.read_csv("QMS_Offs-Scan.txt",
+                         sep="\t",
+                         #usecols=["Time"]
+                         header=None,
+                         )
+        df_offs=df_offs.replace(np.nan, 0)
+
+
+    l=len(df_offs)
+
+    print(l)
+
+       
+
+    if l == 3:
+        mass_value_offs=np.array(df_offs[1:2])
+        mass_value_off=mass_value_offs[0]
+        print(mass_value_offs())
+    else:
+        mass_value_offs=np.array(df_offs[l-2:l-1])
+        mass_value_off=mass_value_offs[0]
+    
+
+#############################################################################################################
+
+###################### Plot der Scans werden abgebildet und den json-dokument hinzugefügt #####################
+I_Scan=np.float64(mass_value[2:-2])
+I_Scan_Offs=np.float64(mass_value_off[2:-2])
+Mass_Scan=mass_no[0]
+Mass_Scan=Mass_Scan[2:-2]
+
+for i in range(len(Mass_Scan)):
+    Mass_Scan[i] = re.sub(r"Mass ", "", Mass_Scan[i]).strip()
+   
+   
+Mass_Scan=np.float64(Mass_Scan)
+
+fig=plt.figure()
+ax=fig.add_axes([0,0,4,2])
+ax.set_xlabel('Masse')
+ax.set_ylabel('QMS-Signal')
+ax.set_yscale('log')
+#plt.plot(1010,4.65e-10, 'bo')
+plt.plot(Mass_Scan,I_Scan, label=r'Floww')
+plt.plot(Mass_Scan,I_Scan_Offs,label=r'Offset' )
+plt.legend()
+
+
+plt.grid()
+
+fig.savefig("Scan.pdf", bbox_inches='tight')
+
+
+
+#############################################################################################################
+
+from collections import OrderedDict
+
+def getMassAverage(filename, tbegin = None, tend = None, trange = None):
+    def error_exit(x):
+        print('ERROR: ', str(x), file=sys.stderr)
+        sys.exit(1)
+    if not trange and (not tbegin or not tend):
+        error_exit('Missing time range')
+    try:
+        d = {}
+        with open(filename, 'r') as f:
+            line = f.readline()
+            dataValid = False
+            while line:
+                if dataValid:
+                    # Ende der Daten
+                    if line.startswith('"[Annotations/User Records'):
+                        dataValid = False
+                    else:
+                        l = line.strip()
+                        a = l.split('\t')# An Tabulatoren trennen
+                        # a[0] = "Time", a[1] = "Scan", a[2] = "Mass 4", a[3] = "Sum Scanned Masses"
+                        if a[0]:
+                            key = a[0].strip('"')
+                            # Timestamp als key für Dictionary
+                            d[key] = a[2]
+                else:
+                    # Beginn der Daten
+                    if line.startswith('"Time"'):
+                        dataValid = True
+                line = f.readline()            
+    except:
+        error_exit("Can't read file: " +  filename)
+    finally:
+        f.close()
+    # Sortieren bei neueren Python-Versionen unnötig?    
+    data = OrderedDict(sorted(d.items()))
+    
+    def doAverage(beg, end):
+        sum = 0.0
+        cnt = 0
+        for key in data:
+            if key >= beg and key < end:
+              #print(key, '-->', data[key])
+              cnt += 1
+              sum += float(data[key])
+        return sum / cnt
+    
+    tb = []
+    te = []
+    res = []
+    
+    if trange:
+        if not isinstance(trange,list):
+            trange = [trange]# Einzelwert zu Array machen
+        for x in trange:
+            a = x.split(' -')
+            tb.append(a[0].strip())
+            te.append(a[1].strip())
+    else:
+        if not isinstance(tbegin,list):
+            tb = [tbegin]# Einzelwert zu Array machen
+        if not isinstance(tend,list):
+            te = [tend]# Einzelwert zu Array machen
+    
+    i = 0
+    while i < len(tb):
+        s = doAverage(tb[i], te[i])
+        res.append(s)
+        i += 1
+    if len(res) == 1:
+        return res[0]# Bei nur einem Wert: kein Array
+    else:
+        return res
+
+trangeArrayTL=list(I_TL_time)
+trangeArrayFM=list(I_FM_time)
+trangeArrayOff=list(I_Offs_time)
+
+xtrangeArray = [
+              '28.07.2022 09:19:19 -28.07.2022 09:21:18 '
+                            
+            ]
+#trangeArray = I_TL_time
+
+x1 = getMassAverage(filename=dateiQMS,trange=trangeArrayTL )
+i = 0
+while i < len(x1):
+    print(i, 'Mass Avarage: ', x1[i])
+    i += 1
+print(x1)
+
+x2 = getMassAverage(filename=dateiQMS,trange=trangeArrayFM )
+i = 0
+while i < len(x2):
+    print(i, 'Mass Avarage: ', x2[i])
+    i += 1
+print(x2)
+
+x3 = getMassAverage(filename=dateiQMS,trange=trangeArrayOff)
+i = 0
+while i < len(x3):
+    print(i, 'Mass Avarage: ', x3[i])
+    i += 1
+print(x3)
+I_TL=np.array(x1)
+I_FM=np.array(x2)
+I_Offs=np.array(x3)
+
+########################################################################################################################################
+
+
+# Temperatur
+lis_T_fm = T_fm.tolist()
+lis_T_room = T_room.tolist()
+lis_T_tl1 = T_tl1.tolist()
+lis_T_tl2 = T_tl2.tolist()
+lis_T_tl3 = T_tl3.tolist()
+lis_T_tl4 = T_tl4.tolist()
+
+
+# Druck
+
+if gauge == 0.01 :
+    lis_p_offs_01 = p_offs_01.tolist()
+    lis_p_fill_01 = p_fill_01.tolist()
+    lis_p_offs_srg = p_offs_srg.tolist()
+    lis_p_fill_srg = p_fill_srg.tolist()
+    
+    
+    
+else:
+    lis_p_offs = p_offs.tolist()
+    lis_p_fill = p_fill.tolist()
+    
+    
+    
+
+
+
+lis_p_ig = p_ig.tolist()
+# I-QMS
+lis_I_TL_time = I_TL_time.tolist()
+lis_I_Offs_time = I_Offs_time.tolist()
+lis_I_FM_time = I_FM_time.tolist()
+# I-QMS
+lis_I_TL = I_TL.tolist()
+lis_I_Offs = I_Offs.tolist()
+lis_I_FM = I_FM.tolist()
+# Datum
+# Datum
+lis_datum = datum.tolist()
+lis_time = time.tolist()
+
+# Ventil
+lis_valve = Valve.tolist()
+
+
+datum_meas = lis_datum[0:1]
+
+
+
+
+if L == 1 :
+    #Leitwert
+    lis_c = L_ar.tolist()
+
+    # Steigung SZ
+    lis_m1 = m1.tolist()
+    lis_m2 = m2.tolist()
+    lis_m3 = m3.tolist()
+    lis_m4 = m4.tolist()
+
+    # Zeitpunkte
+    lis_t1 = t1.tolist()
+    lis_t2 = t2.tolist()
+    lis_t3 = t3.tolist()
+    lis_t4 = t4.tolist()
+
+    # Zeit pro SZ
+    lis_time1 = time1.tolist()
+    lis_time2 = time2.tolist()
+    lis_time3 = time3.tolist()
+
+    # Druck der SZ
+    lis_pmean = pmean.tolist()
+    lis_pmin = pmin.tolist()
+    lis_pmax= pmax.tolist()
+
+    # Druck der SZ
+    lis_h = h.tolist()
+    
+    
+    doc["Calibration"]["Measurement"]["Values"]={"Temperature": [{"Unit": "C","Type": "T-FM","Comment":"Temperatur T ","Value": lis_T_fm},
+                                                                {"Unit": "C","Type": "T-Room","Comment":"Temperatur T","Value": lis_T_room},
+                                                                {"Unit": "C","Type": "T-TL1","Comment":"Temperatur T","Value": lis_T_tl1},
+                                                               {"Unit": "C","Type": "T-TL2","Comment":"Temperatur T","Value":lis_T_tl2},
+                                                               {"Unit": "C","Type": "T-TL2","Comment":"Temperatur T","Value":lis_T_tl3},
+                                                               {"Unit": "C","Type": "T-TL3","Comment":"Temperatur T","Value": lis_T_tl4}],
+                                                "Pressure": [{"Unit": "Pa","Type": "Offset pressure","Value":lis_p_offs},
+                                                             {"Unit": "Pa","Type": "pressure mean","Value":lis_p_fill},
+                                                             {"Unit": "bar","Type": "TL1 pressure ","Value":lis_p_ig}],
+                                                "Date": [{"Unit": "year-month-day","Type": "Datum","Value":lis_datum},
+                                                             {"Unit": "hh:mm:ss","Type": "Messzeit","Value":lis_time}],
+                                                "Valve": [{"Unit": "1","Type": "Connection", "Comment":"Connection of the leak" ,"Value":lis_valve}],
+                                                "Current": [{"Unit": "mbar","Type": "I-TL","Value": lis_I_TL},
+                                                          {"Unit": "mbar","Type": "I-FM","Value": lis_I_FM}, 
+                                                          {"Unit": "mbar","Type": "I-Offs","Value": lis_I_Offs}],
+                                                                                         
+                                               "CurrentTime": [{"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-TL","Value": lis_I_TL_time},
+                                                          {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-FM","Value": lis_I_FM_time}, 
+                                                         {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-Offs","Value": lis_I_Offs_time}]
+                                               
+                                     }
+    doc["Calibration"]["Measurement"]["Date"]=[{"Type": "measurement","Value": datum_meas}]
+
+    doc["Calibration"]["Measurement"]["Values"]["Conductance"]={"t": [{"Unit": "s","Type": "t1","Comment":"Zeitpunkt t1 des 1.SZ","Value": lis_t1},
+                                                                            {"Unit": "s","Type": "t2","Comment":"Zeitpunkt t2 des 2.SZ","Value": lis_t2}, 
+                                                                            {"Unit": "s","Type": "t3","Comment":"Zeitpunkt t3 des 3.SZ","Value": lis_t3},
+                                                                           {"Unit": "s","Type": "t4","Comment":"Zeitpunkt t4 des 4.SZ","Value": lis_t4}],
+                                                                "time": [{"Unit": "s","Type": "time1","Comment":"Zeit t2-t1 von SZ","Value": lis_time1},
+                                                                       {"Unit": "s","Type": "time2","Comment":"Zeit t3-t2 von SZ","Value": lis_time2}, 
+                                                                      {"Unit": "s","Type": "time3","Comment":"Zeit t4-t3 von SZ","Value": lis_time3}],
+                                                                "m": [{"Unit": "Pa/s","Type": "m1","Comment":"Steigung m1 des 1.SZ","Value": lis_m1},
+                                                                       {"Unit": "Pa/s","Type": "m2","Comment":"Steigung m1 des 2.SZ","Value": lis_m2}, 
+                                                                      {"Unit": "Pa/s","Type": "m3","Comment":"Steigung m1 des 3.SZ","Value": lis_m3},
+                                                                       {"Unit": "Pa/s","Type": "m3","Comment":"Steigung m1 des 4.SZ","Value": lis_m3}],
+                                                               "pressure": [{"Unit": "Pa","Type": "pmean","Comment":"Mittelwert von p","Value": lis_pmean},
+                                                                      {"Unit": "Pa","Type": "pmin","Comment":"p_min des SZ","Value": lis_pmin}, 
+                                                                      {"Unit": "Pa","Type": "pmax","Comment":"p_max des SZ","Value": lis_pmax}],
+                                                               "l": [{"Unit": "mm","Type": "l","Comment":"Hub des Verdrängers","Value": lis_h}],
+                                                               "C": [{"Unit": "m^3/s","Type": "Constanter Leitwert ","Value": lis_c}]
+                                                               
+                                                                }
+
+
+
+    
+    
+    print("Constantes Volumen")
+    
+                               
+                                                                
+else:
+    
+    lis_c = L_ar.tolist()
+    if gauge == 0.01 :
+        doc["Calibration"]["Measurement"]["Values"]={"Temperature": [{"Unit": "C","Type": "T-FM ","Comment":"Temperatur T ","Value": lis_T_fm},
+                                                                    {"Unit": "C","Type": "T-Room","Comment":"Temperatur T","Value": lis_T_room},
+                                                                    {"Unit": "C","Type": "T-TL1","Comment":"Temperatur T","Value": lis_T_tl1},
+                                                                   {"Unit": "C","Type": "T-TL2","Comment":"Temperatur T","Value":lis_T_tl2},
+                                                                   {"Unit": "C","Type": "T-TL2","Comment":"Temperatur T","Value":lis_T_tl3},
+                                                                   {"Unit": "C","Type": "T-TL3","Comment":"Temperatur T","Value": lis_T_tl4}],
+                                                    "Pressure": [{"Unit": "DCR","Type": "Offset pressure SRG","Value":lis_p_offs_srg},
+                                                                 {"Unit": "DCR","Type": "Fill pressure SRG ","Value":lis_p_fill_srg},
+                                                                 {"Unit": "Pa","Type": "Offset pressure 01Torr","Value":lis_p_offs_01},
+                                                                 {"Unit": "Pa","Type": "Fill pressure 01Torr","Value":lis_p_fill_01},
+                                                                 {"Unit": "mbar","Type": "TL1 pressure ","Value":lis_p_ig}],
+                                                    "Date": [{"Unit": "year-month-day","Type": "Datum","Value":lis_datum},
+                                                                 {"Unit": "hh:mm:ss","Type": "Messzeit","Value":lis_time}],
+                                                    "Valve": [{"Unit": "1","Type": "Connection", "Comment":"Connection of the leak" ,"Value":lis_valve}],
+                                                    "Current": [{"Unit": "mbar","Type": "I-TL","Value": lis_I_TL},
+                                                              {"Unit": "mbar","Type": "I-FM","Value": lis_I_FM}, 
+                                                              {"Unit": "mbar","Type": "I-Offs","Value": lis_I_Offs}],
+                                                                                             
+                                                   "CurrentTime": [{"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-TL","Value": lis_I_TL_time},
+                                                              {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-FM","Value": lis_I_FM_time}, 
+                                                             {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-Offs","Value": lis_I_Offs_time}]
+                                                   }
+        print("SRG")
+        
+    else:
+        doc["Calibration"]["Measurement"]["Values"]={"Temperature": [{"Unit": "C","Type": "T-FM","Comment":"Temperatur T ","Value": lis_T_fm},
+                                                                    {"Unit": "C","Type": "T-Room","Comment":"Temperatur T","Value": lis_T_room},
+                                                                    {"Unit": "C","Type": "T-TL1","Comment":"Temperatur T","Value": lis_T_tl1},
+                                                                   {"Unit": "C","Type": "T-TL2","Comment":"Temperatur T","Value":lis_T_tl2},
+                                                                   {"Unit": "C","Type": "T-TL2","Comment":"Temperatur T","Value":lis_T_tl3},
+                                                                   {"Unit": "C","Type": "T-TL3","Comment":"Temperatur T","Value": lis_T_tl4}],
+                                                    "Pressure": [{"Unit": "Pa","Type": "Offset pressure","Value":lis_p_offs},
+                                                                 {"Unit": "Pa","Type": " pressure fill","Value":lis_p_fill},
+                                                                
+                                                                 {"Unit": "mbar","Type": "TL1 pressure","Value":lis_p_ig}],
+                                                    "Date": [{"Unit": "year-month-day","Type": "Datum","Value":lis_datum},
+                                                                 {"Unit": "hh:mm:ss","Type": "Messzeit","Value":lis_time}],
+                                                    "Valve": [{"Unit": "1","Type": "Connection", "Comment":"Connection of the leak" ,"Value":lis_valve}],
+                                                    "Current": [{"Unit": "mbar","Type": "I-TL","Value": lis_I_TL},
+                                                              {"Unit": "mbar","Type": "I-FM","Value": lis_I_FM}, 
+                                                              {"Unit": "mbar","Type": "I-Offs","Value": lis_I_Offs}],
+                                                                                             
+                                                   "CurrentTime": [{"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-TL","Value": lis_I_TL_time},
+                                                              {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-FM","Value": lis_I_FM_time}, 
+                                                             {"Unit": "dd.mm.yy hh:mm:ss -dd.mm.yy hh:mm:ss","Type": "I-Offs","Value": lis_I_Offs_time}]
+                                                   }
+        doc["Calibration"]["Measurement"]["Values"]["Conductance"]={  "C": [{"Unit": "m^3/s","Type": "Constanter Leitwert","Value": lis_c}]}
+    print("Constanter Leitwert")
+    
+                                                            
+    
+        
+    
+    
+    
+doc["Calibration"]["Measurement"]["Date"]=[{"Type": "measurement","Value": datum_meas}]
+
+
+    
+
+
+
+lis_mass_no = mass_no.tolist()[0]
+lis_mass_value = mass_value.tolist()
+lis_mass_value_offs = mass_value_offs.tolist()[0]
+
+
+
+
+key_value=dict(zip(def_key, def_value))
+key_value_offs=dict(zip(def_key_offs, def_value_offs))
+
+
+
+doc["Calibration"]["Measurement"]["AuxValues"]={"ScanQMS": [{"Unit": "Mass","Type": "QMS","Comment":"Masse ","Value":lis_mass_no},
+                                                            {"Unit": "mbar","Type": "Current","Comment":"Wert / Masse","Value": lis_mass_value},
+                                                            {"Unit": "mbar","Type": "Current Offset","Comment":"Wert / Masse","Value": lis_mass_value_offs}],
+                                                "DefQMS": [{"Type": "Scan QMS","Value":key_value},
+                                                           {"Type": "Scan Offset QMS","Value": key_value_offs}]}
+
+
+#doc["Calibration"]["Measurement"]["AuxValues"]={"ScanQMS": [{"Unit": "Mass","Type": "QMS ","Comment":"Masse ","Value":lis_mass_no},
+#                                                            {"Unit": "mbar","Type": "Current","Comment":"Wert / Masse","Value": lis_mass_value},
+##                                                            {"Unit": "mbar","Type": "Current Offset","Comment":"Wert / Masse","Value": lis_mass_value_offs}],
+#                                                "DefQMS": [{"Type": "Scan QMS ","Value":key_value},
+#                                                           {"Type": "Scan Offset QMS","Value": key_value_offs}]}
+
+#db.save(doc)
+
+content=pathlib.Path('Scan.pdf').read_bytes() 
+
+db.put_attachment(doc, content, "Scan.pdf" , content_type="'application/pdf")
+
+
+
+
+>>>>>>>> 3935a96522bd6df202a002bc0f35c344c9a917ac:file-to-couchdb_tl1.py
diff --git a/testplot.py b/testplot.py
deleted file mode 100644
index d010a69cbc52931ce73e7ab5aad9932628fb358b..0000000000000000000000000000000000000000
--- a/testplot.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Created on Thu Feb 22 11:21:17 2024
-
-@author: becker07
-"""
-
-from matplotlib import pyplot as plt
-import pathlib
-from statistics import mean
-from datetime import datetime
-from IPython.display import Markdown as md
-import numpy as np
-import re
-import math
-import statistics
-import pandas as pd
-import json
-import couchdb 
-import PyPDF2
-
-
-couch = couchdb.Server('http://a73434.berlin.ptb.de:5984')
-db = couch['vl_db'] # existing
-#json_file = "cal-" + year + "-fm1-" + "-" + cal_cert + "_" + no
-
-
-json_file = "cal-2024-fm1-kk-75565_0001"
-print(json_file)
-
-
-doc = db.get(json_file) 
-
-
-
-
-I_Scan_Offs=np.array(doc["Calibration"]["Measurement"]["AuxValues"]["ScanQMS"][2]["Value"])
-I_Scan_Offs=np.float64(I_Scan_Offs[2:-2])
-I_Scan=np.array(doc["Calibration"]["Measurement"]["AuxValues"]["ScanQMS"][1]["Value"])
-I_Scan=np.float64(I_Scan[2:-2])
-Mass_Scan=np.array(doc["Calibration"]["Measurement"]["AuxValues"]["ScanQMS"][0]["Value"])
-Mass_Scan=Mass_Scan[2:-2]
-
-for i in range(len(Mass_Scan)):
-    Mass_Scan[i] = re.sub(r"Mass ", "", Mass_Scan[i]).strip()
-   
-    
-Mass_Scan=np.float64(Mass_Scan)
-
-fig=plt.figure()
-ax=fig.add_axes([0,0,4,2])
-ax.set_xlabel('Masse')
-ax.set_ylabel('QMS-Signal')
-ax.set_yscale('log')
-#plt.plot(1010,4.65e-10, 'bo')
-plt.plot(Mass_Scan,I_Scan, label=r'Flow')
-plt.plot(Mass_Scan,I_Scan_Offs,label=r'Offset' )
-plt.legend()
-
-
-plt.grid()
-
-fig.savefig("Scan.pdf", bbox_inches='tight')
-
-content=pathlib.Path('Scan.pdf').read_bytes() 
-
-db.put_attachment(doc, content, "Scan.pdf" , content_type="'application/pdf")
-
diff --git a/tl.ini b/tl.ini
new file mode 100644
index 0000000000000000000000000000000000000000..5a0a1bd822504c53b8679b8bc3e650914b29688e
--- /dev/null
+++ b/tl.ini
@@ -0,0 +1,18 @@
+[path]
+path_ks=C:\\Users\\becker07\\kalibrierschein\\ks-
+path_files=C:\\Users\\becker07\\python\\TL1\\
+
+
+[couch]
+couch = http://a73434.berlin.ptb.de:5984
+db = vl_db
+
+[api]
+API_HOST_URL = https://elabftw.ptb.de/api/v2
+API_KEY = Beispiel
+
+
+
+
+
+ 
\ No newline at end of file
diff --git a/writeLaTex-ks-TLV.py b/writeLaTex-ks-TLV.py
index 4f31d8e5f108e0b787c9e4017546fe3abeb00e95..67439a160f3729d635b41507b2bcb48f82043007 100644
--- a/writeLaTex-ks-TLV.py
+++ b/writeLaTex-ks-TLV.py
@@ -1,35 +1,41 @@
-# -*- coding: utf-8 -*-
-"""
-Created on Tue Aug 23 09:45:09 2022
-
-@author: becker07
-"""
-
 import time
 import couchdb 
 from datetime import date
-couch = couchdb.Server('http://a73434.berlin.ptb.de:5984')
-db = couch['vl_db'] # existing
+try:
+    from configparser import ConfigParser
+except ImportError:
+    from ConfigParser import ConfigParser  # ver. < 3.0
+    
+    
 
+configtl1 = ConfigParser()
+ini_values = ConfigParser()
+# parse existing file
+configtl1.read('tl.ini')
+ini_values.read('inputs.ini')
+# read values from a section
 
-## Eingabe von:
-#    - Kalibrierscheinnummer
-#    - Jahr der Kalibrierung 
-#    - laufende Nummer der Kalibrierung
+cal_cert = ini_values.get('input_cer', 'cal_cert')
+year = ini_values.get('input_gen',  'year')
+year_str2=year[2:]
+no = ini_values.get('input_gen', 'no')
+path=configtl1.get('path', 'path')
+server=configtl1.get('couch', 'couch')
+db_vl=configtl1.get('couch', 'db')
 
-cal_cert = "75552"
-year = "2024"
-year_Mark=year[2:]
-print(year_Mark)
-no = "0001"
-CertificateDate = str(date.today())
+couch = couchdb.Server(server)
+db = couch[db_vl] # existing
 
 
+CertificateDate = str(date.today())
+
 json_file_cer = "cer-" + year + "-" + cal_cert 
 
 print(json_file_cer)
 
 
+### Kontrolle ob schon ein cer existiert #########
+
 id_cer = 0   
     
 mango = {'selector': {'_id':json_file_cer}}
@@ -41,10 +47,11 @@ print(id_cer)
 
 doc = {'_id': json_file_cer}
 
+
 if id_cer == 0:
     db.save(doc)
-    print ( "Warten! 30 Sekunden" )
-    time.sleep ( 30 )
+    print ( "Warten! 5 Sekunden" )
+    time.sleep ( 5 )
     print ( json_file_cer," ist in der Couch angelegt" )
     
 else:
@@ -52,8 +59,7 @@ else:
 
 
 id_ = "cal-" + year + "-fm1-kk-" + cal_cert + "_" + no
-ks = "C:\\Users\\becker07\\kalibrierschein\\ks-" + cal_cert + "-" + year + ".tex"
-
+ks = path + cal_cert + "-" + year + ".tex"
 cer = "cer-" + year + "-" + cal_cert
 
 json_file_cal = id_
@@ -62,19 +68,24 @@ doc_cal = db.get(json_file_cal)
 doc_cer = db.get(json_file_cer) 
 
 
-print(json_file_cal)
-
 
+ ##### Daten aus dem cal Dokument werden eingelesen#######
 
-##### Meta #######
-
+std = doc_cal["Calibration"]["ToDo"]["Standard"]
 kind = doc_cal["Calibration"]["ToDo"]["Type"]
 gas = doc_cal["Calibration"]["ToDo"]["Gas"]
 lang = doc_cal["Calibration"]["Customer"]["Lang"]
+todo = doc_cal["Calibration"]["ToDo"]["Type"]
+
+
+
+
+ 
+
+print(lang)
 calibration_type = "KK"
 last_cert_no = doc_cal["Calibration"]["Presettings"]
 
-
 ###### überprüfen ob eine letztes Cal-Zeichen gibt  #########################
 
 if "LastCalibrationYear" in last_cert_no:
@@ -92,21 +103,6 @@ else:
 
 
 
-
-
-
-##### Titlepage #######
-
-
-MeasurementDateBegin = doc_cal["Calibration"]["Measurement"]["Date"][0]["Value"]
-MeasurementDateBegin = MeasurementDateBegin[0]
-MeasurementDateEnd = doc_cal["Calibration"]["Measurement"]["Date"][0]["Value"]
-MeasurementDateEnd = MeasurementDateEnd[0]
-
-
-CountryCode= lang
-DeviceClass= "TLV"
-
 Standard = doc_cal["Calibration"]["ToDo"]["Standard"]
 Land= doc_cal["Calibration"]["Customer"]["Address"]["Land"]
 
@@ -121,156 +117,194 @@ Zipcode= doc_cal["Calibration"]["Customer"]["Address"]["Zipcode"]
 ObjectOfCalibration= doc_cal["Calibration"]["CustomerObject"]["Type"]
 Producer= doc_cal["Calibration"]["CustomerObject"]["Device"]["Producer"]
 Type= doc_cal["Calibration"]["CustomerObject"]["Device"]["Type"]                ##########   Type
-Object= doc_cal["Calibration"]["CustomerObject"]["NameCer"]                        ##########   Gegenstand/Object
+Object= doc_cal["Calibration"]["CustomerObject"]["Type"]                        ##########   Gegenstand/Object
 Serial= doc_cal["Calibration"]["CustomerObject"]["Name"]                        ##########   Kennummer   
 Examiner= doc_cal["Calibration"]["Measurement"]["Maintainer"]
 ByOrder= "Dr. Matthias Bernien"
 MeasurementDate= doc_cal["Calibration"]["Result"]["Formula"]["MeasurementDate"]
 QMS= doc_cal["Calibration"]["Result"]["Formula"]["QMS"]
 
-print(MeasurementDate)
+
 
 obj ='\\object{'+ Object + '}\n'
 manufacturer = '\\manufacturer{' + Producer +' }\n'
 typ = '\\type{' +  Type + '}\n'
 serialNo = '\\serialNo{' + Serial + '}\n'
-applicant = '\\applicant{{' + Name + '}\n {' + Street + '} \n {' + Zipcode +' ' + Town +'}\n {' + Land+'}}\n'
+applicant = '\\applicant{{' + Name + '}\n {' + Street + '} \n {' + Zipcode + Town +'}\n {' + Land +'}}\n'
 refNo = '\\refNo{ ' + ReferenceNo + '}\n'
-calibMark = '\\calibMark{ ' + Certificate + ' PTB '  + year_Mark + '}\n'
-print(calibMark)
+calibMark = '\\calibMark{ ' +' ' + Certificate + ' PTB ' + year_str2 + '}\n'
 calibDate = '\\calibDate{' + MeasurementDate + '}\n'
 examiner = '\\examiner{' + Examiner + '}\n'
 certificateDate = '\\certificateDate{' + CertificateDate + '}\n'
 
-##################section Beschreibung zum Kalibriergerät
 
 
-if (sectionDiscription_noyes!= 'yes'):
-    
-    sectionDiscription_2= " Dies ist die erste von der PTB durchgeführte Kalibrierung."
-    sectionDiscription_2_en= "This is the first calibration at PTB."
-    print(" 1. durchgeführte Kalibrierung")
-
-else:
-   
-    sectionDiscription_2= " Die von der PTB zuletzt durchgeführten Kalibrierung ist im Kalibrierschein " +  last_cert + " beschrieben."
-    sectionDiscription_2_en= " The previous calibration at PTB had been carried out " +  last_cert_year + ' with the calibration mark ' + last_cert + " ."
 
+##################  Ergebnisse ###################################################
+NoOfMeasurements= doc_cal["Calibration"]["Result"]["Formula"]["NoOfMeasurements"]
+FlowMol= doc_cal["Calibration"]["Result"]["Formula"]["FlowMol"]
+FlowpV23= doc_cal["Calibration"]["Result"]["Formula"]["FlowpV23"]
+FlowpV2X= doc_cal["Calibration"]["Result"]["Formula"]["FlowpV2X"]
+TemperatureTL= doc_cal["Calibration"]["Result"]["Formula"]["TemperatureTL"]
+TemperatureTLx= doc_cal["Calibration"]["Result"]["Formula"]["TemperatureTLx"]
 
+Gauge= doc_cal["Calibration"]["Result"]["Formula"]["Gauge"]
+LeakUncertainty= doc_cal["Calibration"]["Result"]["Formula"]["LeakUncertainty"]
+print("TLX= ",TemperatureTLx)
 TextDE= doc_cal["Calibration"]["CustomerObject"]["Text"]["description"]["de"]
 TextEN= doc_cal["Calibration"]["CustomerObject"]["Text"]["description"]["en"]
 
-sectionText_title_de = 'Beschreibung zum Kalibriergerät '
-sectionText_title_en = 'Description relating to calibration device'
-sectionTitleText_de = '\\section{' + sectionText_title_de  + '\\linebreak {\\small \\emph{' + sectionText_title_en + 'Description relating to calibration device}}}\n' + TextDE + sectionDiscription_2+'\n' + '\\begin{english}' + TextEN + sectionDiscription_2_en +'\\end{english} \n'
-sectionTitleText_en = '\\section{' + sectionText_title_en  + ' }\n' + TextEN +sectionDiscription_2_en +'\n' 
 
+###############################################################################################################################################################
 
 
 
 
 
+#######  Überschriften ######################
 
-#########################  Messverfahren #########################################################################
+########   Deutsch ##########################
 
+sectionDescriptionTitle = 'Beschreibung zum Kalibriergerät'
 sectionTitelProcedure = 'Kalibrierverfahren '
-sectionTitelProcedure_en = 'Calibration procedure'
-sectionTitelProcedure_text_en = '\\section{' + sectionTitelProcedure_en + '}\n '
-sectionTitelProcedure_text = '\\section{' + sectionTitelProcedure + '\\linebreak {\\small \\emph{' + sectionTitelProcedure_en + '}}}\n '
+sectionTitelResult = 'Messergebnis '
+sectionTitelUncertainty = 'Unsicherheit '
 
-sectionProcedure1='Der aus dem thermostatisierten Testleck TL austretende Gasfluss wird mit Hilfe  eines Massenspektrometers mit einem annähernd gleich groß eingestellten  Gasfluss \\(q_{\\text{mol, FM}}\\) verglichen, dessen Größe mit einem  Durchflussmesser (Flowmeter FM) bestimmt wird. Die Durchflussmessung erfolgt  bei konstantem Druck \\(p_\\text{FM}\\) und konstanter Temperatur  \\(T_{\\text{FM}}\\).\n '
-sectionProcedure1_en ='The gas flow from the leak TL is compared with a gas flow \\(q_{\\text{mol, FM}}\\) of about the same flow rate from a flow meter FM by a mass spectrometer. The flow measurement is operated at constant pressure  \\(p_{\\text{FM}}\\) and constant (absolute) temperature \\(T_{\\text{FM}}\\). \n'
-sectionProcedureE1 = ' \\[ q_{\\text{mol, FM}}  = p_{\\text{FM}} \\cdot C \\cdot \\frac{1}{R \\cdot  T_{\\text{FM}}} \\]  '
-sectionProcedure2=' Der Druck \\(p_{\\text{FM}}\\) wurde mit einem kapazitiven  Membranvakuummeter gemessen. Dieses Gerät ist durch Vergleich mit einem  Primärnormal der PTB kalibriert worden. Der Leitwert \\(C\\) wird aus der  zeitlichen Volumenänderung (\\(\\Delta V/\\Delta t\\)) eines zusammendrückbaren,  kalibrierten Federbalgs (\\(\\Delta V\\)) und einer elektronischen Uhr (\\(\\Delta  t\\)) ermittelt. Die molare Gaskonstante \\(R\\) hat den Wert  83,145~\\(\\text{mbar}\\)~\\(\\text{l}\\)~\\(\\text{mol}^{-1}\\)~\\(\\text{K}^{-1}\\). \n '
-sectionProcedure2_en='  The pressure \\(p_{\\text{FM}}\\) is measured with a capacitance diaphragm gauge. This gauge is calibrated by comparison with a primary standard of PTB. The conductance \\(C\\) of the capillary integrated in the flow meter is obtained from the temporal volume change (\\(\\Delta V/\\Delta t\\)) that is needed to keep \\(p_\\text{FM}\\) constant. It is measured by means of a calibrated bellow and an electronic clock. The molar gas constant \\(R\\) has the value 83.145~\\(\\text{mbar}\\)~\\(\\text{l}\\)~\\(\\text{mol}^{-1}\\)~\\(\\text{K}^{-1}\\). '
-sectionProcedureE3 = ' \\[ q_{\\text{mol, TL}} = q_{\\text{mol, FM}} \\cdot \\frac{S_{\\text{TL}}}{S_{\\text{FM}}} \\]  '
-sectionProcedure3=' Die Leckrate \\(q_{\\text{mol, TL}}\\)  des Testlecks wird nach folgender Beziehung berechnet:'
-sectionProcedure3_en=' The molar leak rate \\(q_{\\text{mol, TL}}\\) of the test leak can be calculated by the following equation:'
-sectionProcedure4=' mit \\(S_\\text{TL}\\) dem Signal am Massenspektrometer für den Gasfluss des  Testlecks und \\(S_\\text{FM}\\) dem Signal am Massenspektrometer für den  eingestellten Vergleichsgasfluss.'
-sectionProcedure4_en=' whereby \\(S_{\\text{TL}}\\) is the signal at the mass spectrometer for the gas flow from the test leak and \\(S_{\\text{FM}}\\) the signal at the mass spectrometer for the gas flow from the flow meter.'
 
 
 
-sectionProcedure_text= sectionProcedure1 + sectionProcedure2 +'\\begin{english}' + sectionProcedure1_en + sectionProcedure2_en + '\\end{english}' + sectionProcedureE1   + sectionProcedure3  + '\\begin{english}' + sectionProcedure3_en + '\\end{english} '+ sectionProcedureE3 + sectionProcedure4 + '\\begin{english}' +  sectionProcedure4_en + '\\end{english} '
-sectionProcedure_text_en= sectionProcedure1_en  + sectionProcedure2_en + sectionProcedureE1  + sectionProcedure3_en  + sectionProcedureE3  + sectionProcedure4_en + '\n'
+########   Englisch ##########################
 
+sectionDescriptionTitle_en = 'Description relating to calibration device'
+sectionTitelProcedure_en = 'Calibration procedure '
+sectionTitelResult_en = 'Measurement results'
+sectionTitelUncertainty_en = 'Uncertainty of Calibration'
 
 
 
-##################  Ergebnisse ###################################################
+#######  Überschriften         Ende   ######################
 
-NoOfMeasurements= doc_cal["Calibration"]["Result"]["Formula"]["NoOfMeasurements"]
-FlowMol= doc_cal["Calibration"]["Result"]["Formula"]["FlowMol"]
-FlowpV23= doc_cal["Calibration"]["Result"]["Formula"]["FlowpV23"]
-FlowpV2X= doc_cal["Calibration"]["Result"]["Formula"]["FlowpV2X"]
-TemperatureTL= doc_cal["Calibration"]["Result"]["Formula"]["TemperatureTL"]
-TemperatureTLx= doc_cal["Calibration"]["Result"]["Formula"]["TemperatureTLx"]
 
+#######                 Formeln                     ####################
+q_mol_FM_allg = ' \\[ q_\\text{mol, FM} = p_{\\text{FM}} ~ C ~  \\frac{1}{RT_{\\text{FM}}}\\]  '
+q_mol_TL_allg = ' \\[ q_\\text{mol, TL} = q_\\text{mol, FM} ~ \\frac{S_\\text{TL}}{S_\\text{FM}}\\] \n '
+q_mol_Val= 'q_\\text{mol}(\\vartheta_\\text{TL}) =\\SI{   ' + FlowMol + ' }{\\mol\\per\\second}'
+q_pV_allg = ' \\[ q_{pV}(\\vartheta_\\text{Ch}) = q_{\\text{mol}} ~ R ~ (\\vartheta_\\text{Ch} + T_0) \\]  '    
+q_pV_23C = 'q_{pV}(\\SI{23}{\\degreeCelsius})= \\num{' + FlowpV23 + '} ~\\text{Pa}~\\text{m}^3~\\text{s}^{-1}'
+q_pV_2X = 'q_{pV}(\\SI{23}{\\degreeCelsius})= \\num{' + FlowpV2X + '} ~\\text{Pa}~\\text{m}^3~\\text{s}^{-1}'  
 
-QMS= doc_cal["Calibration"]["Result"]["Formula"]["QMS"]
-Gauge= doc_cal["Calibration"]["Result"]["Formula"]["Gauge"]
-LeakUncertainty= doc_cal["Calibration"]["Result"]["Formula"]["LeakUncertainty"]
-print("TLX= ",TemperatureTLx)
+######## Tabellen um die Formeln zu zentriert. Bei den deutsch englischen Kalibrierschein stehen beide Ergebnisse direkt untereinander###########################
 
-sectionTitelMeasurement = 'Messergebnis '
-sectionTitelMeasurement_en = 'Measurement results'
-sectionTitelMeasurement_text_en = '\\section{' + sectionTitelMeasurement_en + '}\n '
-sectionTitelMeasurement_text = '\\section{' + sectionTitelMeasurement + '\\linebreak {\\small \\emph{' + sectionTitelMeasurement_en + '}}}\n '
+tab_q_mol_Val= '\\begin{center}\\begin{tabular}[h]{c} $$$' + q_mol_Val + '$$$  \\\\ $$$\\begin{english} ' + q_mol_Val + ' \\end{english}$$$  \\end{tabular}\\end{center} '
+tab_q_mol_Val_en= ' \\[ ' + q_mol_Val + '\\] \n'
 
+tab_q_pV_Val= '\\begin{center}\\begin{tabular}[h]{c} $$$' + q_pV_23C + '$$$  \\\\ $$$\\begin{english} '+ q_pV_23C + '\\end{english}$$$  \\end{tabular}\\end{center}'
+tab_q_pV_Val_en= ' \\[ '  + q_pV_23C + '\\] \n'
 
-sectionResultMol = 'Mit dem thermostatisierten Testleck wurden insgesamt ' +  NoOfMeasurements + '~Leckratenbestimmungen bei einer Testlecktemperatur von  \\( \\vartheta_\\text{TL}= \\SI{' + TemperatureTL + '}{\\degreeCelsius} \\) durchgeführt. Der Mittelwert ergab die (molare) Leckrate:   '
-sectionResultMol_en = NoOfMeasurements + '~measurements were carried out at a leak temperature of \\( \\vartheta_\\text{TL}= \\SI{' + TemperatureTL + '}{\\degreeCelsius} \\) (thermostated). The mean leak rate (molar flow) was determined to: '
-sectionResultMol_pup_en = NoOfMeasurements + '~measurements were carried out at a leak temperature of \\( \\vartheta_\\text{TL}= \\SI{' + TemperatureTL + '}{\\degreeCelsius} \\) (thermostated). The mean leak rate (molar flow) for relativ pressure \\( p_{\\text{up}}=\\SI{0.0}{\\bar} \\) (leak indication) at the upstream pressure side was determined to: '
 
-sectionResultMolVal= '\\[ q_\\text{mol}(\\vartheta_\\text{TL}) =\\SI{' + FlowMol + '}{\\mol\\per\\second} \\]  '
-sectionResultMolVal_en= '\\( q_\\text{mol}(\\vartheta_\\text{TL}) =\\SI{' + FlowMol + '}{\\mol\\per\\second} \\)  '
-sectionResultpV = 'Daraus kann für den Ort mit einer Temperatur \\(\\vartheta_\\text{Ch}\\) in \\si{\\degreeCelsius}, an dem sich der Prüfling befindet und mit \\(T_0 = \\SI{273.15}{\\kelvin}\\), der \\(pV\\)-Durchfluss nach folgender Beziehung berechnet werden.' 
-sectionResultpV_en = 'From this the \\(pV\\)-flow  can be calculated for a place at a temperature \\(\\vartheta_\\text{Ch}\\) (in \\si{\\degreeCelsius}), where a device under test is mounted and  \\(T_0 = \\SI{273.15}{\\kelvin}\\), by the equation:' 
-sectionResultpVVal = '\\[q_{pV}(\\vartheta_\\text{Ch}) = q_{\\text{mol}}(\\vartheta_\\text{TL})\\cdot R \\cdot (\\vartheta_\\text{Ch} + T_0)\\] '
- 
-sectionResultpV_T = 'Bei einer Kammertemperatur von \\( \\vartheta_\\text{TL}= \\SI{23}{\\degreeCelsius} \\) beträgt die Leckrate \\( q_{pV}(\\SI{23}{\\degreeCelsius}) \\):'
-sectionResultpV_T_en = 'At a chamber temperature \\(\\vartheta_\\text{Ch}=\\SI{23}{\\degreeCelsius}\\) the leak rate \\(q_{pV}(\\SI{23}{\\degreeCelsius})\\) will be:'
+########        Formeln        Ende                 ######################
 
-sectionResultpV_Tx = 'und bei einer Kammertemperatur von \\( \\vartheta_\\text{TL}= \\SI{'+ TemperatureTLx +'}{\\degreeCelsius} \\) beträgt die Leckrate \\( q_{pV}(\\SI{'+ TemperatureTLx +'}{\\degreeCelsius}) \\):'
-sectionResultpV_Tx_en = 'and at a chamber temperature \\(\\vartheta_\\text{Ch}=\\SI{'+ TemperatureTLx +'}{\\degreeCelsius}\\) the leak rate \\(q_{pV}(\\SI{'+ TemperatureTLx +'}{\\degreeCelsius})\\) will be:'
 
-sectionResultpVVal_T23 = ' \\[q_{pV}(\\SI{23}{\\degreeCelsius})= \\num{' + FlowpV23 + '} ~\\text{Pa}~\\text{m}^3~\\text{s}^{-1}\\]'
-sectionResultpVVal_T23_en = '\\( q_{pV}(\\SI{23}{\\degreeCelsius})= \\num{' + FlowpV23 + '} ~\\text{Pa}~\\text{m}^3~\\text{s}^{-1}\\)'
-sectionResultpVVal_Tx = ' \\[q_{pV}(\\SI{' + TemperatureTLx + '}{\\degreeCelsius})= \\num{' + FlowpV2X + '} ~\\text{Pa}~\\text{m}^3~\\text{s}^{-1}\\]'
-sectionResultpVVal_Tx_en = ' \\( q_{pV}(\\SI{'+ TemperatureTLx +'}{\\degreeCelsius})= \\num{' + FlowpV2X + '} ~\\text{Pa}~\\text{m}^3~\\text{s}^{-1}\\)'
 
+###### 1. Section: Beschreibung zum Kalibriergerät  ###################
 
-sectionResultU = 'Die relative Unsicherheit \\(U\\) der angegebenen Leckraten beträgt  \\( \\SI{'+ LeakUncertainty +'}{\\percent} \\).' 
-sectionResultU_en = 'The relative uncertainty \\(U\\) of the stated leak rate is    \\( \\SI{'+ LeakUncertainty +'}{\\percent} \\). ' 
 
+sectionDiscription_1= TextDE ###### Beschreibung aus dem cal-Dokument
+sectionDiscription_1_en= TextEN ###### Beschreibung aus dem cal-Dokument
+
+
+if (sectionDiscription_noyes!= 'yes'):
+    
+    sectionDiscription_2= " Dies ist die erste von der PTB durchgeführte Kalibrierung."
+    sectionDiscription_2_en= "This is the previous calibration at PTB."
+    print(" 1. durchgeführte Kalibrierung")
 
-sectionResult = sectionResultMol + sectionResultMolVal  +'\\begin{english}' + sectionResultMol_en + sectionResultMolVal_en + '\\end{english}'  + sectionResultpV + '\\begin{english}' + sectionResultpV_en +'\\end{english}' + sectionResultpVVal + '\\linebreak ' + sectionResultpV_T + sectionResultpVVal_T23   + '\\begin{english}' + sectionResultpV_T_en + sectionResultpVVal_T23_en  + '\\end{english}' +   sectionResultU + '\\begin{english}' +  sectionResultU + '\\end{english}'
-sectionResult_Tx = sectionResultMol + sectionResultMolVal  +'\\begin{english}' + sectionResultMol_en + sectionResultMolVal_en + '\\end{english}'  + sectionResultpV + '\\begin{english}' + sectionResultpV_en +'\\end{english}' + sectionResultpVVal + sectionResultpV_T + sectionResultpVVal_T23   + sectionResultpV_Tx + sectionResultpVVal_Tx + '\\begin{english}' + sectionResultpV_T_en + sectionResultpVVal_T23_en + sectionResultpV_Tx_en + sectionResultpVVal_Tx_en + '\\end{english}' + sectionResultU + '\\begin{english}' +  sectionResultU + '\\end{english}'
+else:
+   
+    sectionDiscription_2= " Die von der PTB zuletzt durchgeführten Kalibrierung ist im Kalibrierschein " +  last_cert + " beschrieben."
+    sectionDiscription_2_en= " The previous calibration at PTB had been carried out " +  last_cert_year + ' with the calibration mark ' + last_cert + " ."
+    
+    
+    
 
+sectionDiscription_1_en= TextEN ###### Beschreibung aus dem cal-Dokument
 
-sectionResult_en = sectionResultMol_en + sectionResultMolVal + sectionResultpV_en + sectionResultpVVal  + sectionResultpV_T_en + sectionResultpVVal_T23
-#sectionResult_en = sectionResultMol_pup_en + sectionResultMolVal + sectionResultpV_en + sectionResultpVVal  + sectionResultpV_T_en + sectionResultpVVal_T23
+sectionDiscription = '\\section{' + sectionDescriptionTitle + '\\linebreak {\\small \\emph{' + sectionDescriptionTitle_en + '}}}\n' + sectionDiscription_1 + sectionDiscription_2 + '\n' + '\\begin{english}' + TextEN + sectionDiscription_2_en + '\\end{english} \n'
+sectionDiscription_en = '\\section{'  + sectionDescriptionTitle_en +'}\n'  + TextEN + sectionDiscription_2_en 
 
-######################################## Unsicherheit ######################################################
 
-sectionU = 'Angegeben ist die erweiterte Messunsicherheit \\(U\\), die sich aus der Standardmessunsicherheit durch Multiplikation mit dem Erweiterungsfaktor \\(k = 2\\)  ergibt. Sie wurde gemäß dem „Guide to the Expression of Uncertainty in Measurement (GUM)“ ermittelt. Der Wert der Messgröße liegt dann im Regelfall mit einer Wahrscheinlichkeit von annähernd \\SI{95}{\\percent} im zugeordneten Überdeckungsintervall.\\n '
-sectionU_en = 'The uncertainty \\(U\\) stated is the expanded measurement uncertainty obtained by multiplying the standard measurement uncertainty by the coverage factor \\(k = 2\\). It has been determined in accordance with the  “Guide to the Expression of Uncertainty in Measurement (GUM)”. The value of the measurand then normally lies, with a probability of approximately \\SI{95}{\\percent} within the attributed coverage interval.'
+print(sectionDiscription, " Discription funktioniert")
 
-sectionU_text = sectionU + '\\begin{english} ' + sectionU_en + '\\end{english}'
-sectionU_text_en = sectionU_en
 
-sectionTitelUncertainty = 'Unsicherheit '
-sectionTitelUncertainty_en = 'Uncertainty of Calibration'
-sectionTitelUncertainty_text_en = '\\section{' + sectionTitelUncertainty_en + '} '
-sectionTitelUncertainty_text = '\\section{' + sectionTitelUncertainty + '\\linebreak {\\small \\emph{' + sectionTitelUncertainty_en + '}}}'
+#######     2. Section: Procedure   ###################################
 
 
+sectionProcedure1='''Der aus dem thermostatisierten Testleck TL austretende Gasfluss \\(q_{\\text{mol, TL}}\\) wird mit Hilfe eines Massenspektrometers mit einem annähernd gleich groß eingestellten Gasfluss \\(q_{\\text{mol, FM}}\\) 
+verglichen, dessen Größe mit einem Durchflussmesser (Flowmeter FM) bestimmt wird. Die Durchflussmessung erfolgt bei konstantem Druck \\(p_{\\text{FM}}\\) und konstanter Temperatur \\(T_{\\text{FM}}\\). Der Druck \\(p_{\\text{FM}}\\) wird
+ mit einem kapazitiven Membranvakuummeter gemessen. Dieses Gerät ist durch einen Vergleich mit einem Primärnormal der PTB kalibriert worden. Der Leitwert \\(C\\) wird aus der zeitlichen Volumenänderung (\\(\\Delta V/\\Delta t\\))
+ eines zusammendrückbaren, kalibrierten Federbalgs (\\(\\Delta V\\)) und einer elektronischen Uhr (\\(\\Delta t\\)) ermittelt. Die molare Gaskonstante \\(R\\) hat den Wert 8,3145~\\(\\text{Pa}\\)~\\(\\text{m}^3\\)~\\(\\text{mol}^{-1}\\)~\\(\\text{K}^{-1}\\).'''
+
+sectionProcedure2=' Die Leckrate \\(q_{\\text{mol, TL}}\\) des Testlecks wird nach folgender Beziehung berechnet:\n '
+sectionProcedure3=' mit \\(S_{\\text{TL}}\\) dem Signal am Massenspektrometer für den Gasfluss des Testlecks und \\(S_{\\text{FM}}\\) dem Signal am Massenspektrometer für den eingestellten Vergleichsgasfluss.'
+
+
+sectionProcedure1_en ='''The gas flow from the leak TL \\(q_{\\text{mol, TL}}\\) is compared with a gas flow \\(q_{\\text{mol, FM}}\\) of about the same flow rate from a flow meter FM by a
+mass spectrometer. The flow measurement is operated at constant pressure \\(p_{\\text{FM}}\\) and constant (absolute) temperature \\(T_{\\text{FM}}\\).
+The pressure \\(p_{\\text{FM}}\\) is measured with a capacitance diaphragm gauge. This gauge is calibrated by comparison with a primary
+standard of PTB. The conductance \\(C\\) of the capillary integrated in the flow meter is obtained from the temporal volume change
+(\\(\\Delta V/\\Delta t\\)) that is needed to keep \\(p_{\\text{FM}}\\) constant. It is measured by means of a calibrated bellow (\\(\\Delta V\\)) and an electronic clock (\\(\\Delta t\\)). The
+molar gas constant \\(R\\) has the value 8.3145~\\(\\text{Pa}\\)~\\(\\text{m}^3\\)~\\(\\text{mol}^{-1}\\)~\\(\\text{K}^{-1}\\). '''
+sectionProcedure2_en='The molar leak rate \\(q_{\\text{mol, TL}}\\) of the test leak can be calculated by the following equation:'
+sectionProcedure3_en=' whereby \\(S_{\\text{TL}}\\) is the signal at the mass spectrometer for the gas flow from the test leak and \\(S_{\\text{FM}}\\) the signal at the mass spectrometer for the gas flow from the flow meter.'
+
+
+sectionProcedure = '\\section{' + sectionTitelProcedure + '\\linebreak {\\small \\emph{' + sectionTitelProcedure_en + '}}}\n' + sectionProcedure1 + '\\begin{english}' + sectionProcedure1_en + '\\end{english} \n' + q_mol_FM_allg + sectionProcedure2 + '\\begin{english}' + sectionProcedure2_en + '\\end{english} \n' + q_mol_TL_allg + sectionProcedure3 + '\\begin{english}' + sectionProcedure3_en +'\\end{english} \n'
+sectionProcedure_en = '\\section{' + sectionTitelProcedure_en + '}\n'  + sectionProcedure1_en  + q_mol_FM_allg + sectionProcedure2_en  + q_mol_TL_allg  + sectionProcedure3_en 
+
+
+#######     3. Section: Result   ###################################
+
+sectionResult1 = 'Mit dem thermostatisierten Testleck wurden insgesamt ' + NoOfMeasurements + ' Leckratenbestimmungen bei einer Testlecktemperatur von \\( \\vartheta_\\text{TL}= \\num{ ' + TemperatureTL + '}\\pm \\SI{0.1}{\\degreeCelsius} \\) durchgeführt.\n Der Mittelwert ergab die (molare) Leckrate:'
+sectionResult2 = 'Daraus kann für den Ort mit einer Temperatur \\(\\vartheta_\\text{Ch}\\) in \\si{\\degreeCelsius}, an dem sich das Testleck befindet, mit \\(T_0 = \\SI{273.15}{\\kelvin}\\), der \\(pV\\)-Durchfluss nach folgender Beziehung berechnet werden.'
+sectionResult3 = 'Bei einer Kammertemperatur von \\( \\vartheta_\\text{Ch}= \\SI{ 23 }{\\degreeCelsius} \\) ergibt sich ein \\(pV\\)-Durchfluss \\(q_{pV}\\) '
+sectionResult3_TX = 'Bei Kammertemperaturen von \\( \\vartheta_\\text{Ch}= \\SI{ 23 }{\\degreeCelsius} \\) und \\( \\vartheta_\\text{Ch}= \\SI{' + TemperatureTLx + ' }{\\degreeCelsius} \\) ergeben sich \\(pV\\)-Durchflüsse \\(q_{pV}\\) von' 
+sectionResult4 = 'Die relative Unsicherheit \\(U\\) der angegebenen Leckraten beträgt  \\( \\SI{'+ LeakUncertainty +'}{\\percent} \\).' 
+
+
+sectionResult1_en = NoOfMeasurements  + ' measurements were carried out at a leak temperature \\( \\vartheta_\\text{TL}= \\num{ ' + TemperatureTL + '}\\pm \\SI{0.1}{\\degreeCelsius} \\) (thermostated). The mean leak rate (molar flow) was determined to:'
+sectionResult2_en = ' From this the \\(pV\\)-flow  can be calculated for a place at a temperature \\(\\vartheta_\\text{Ch}\\) (in \\si{\\degreeCelsius}), where a device under test is mounted and  \\(T_0 = \\SI{273.15}{\\kelvin}\\), by the equation ' 
+sectionResult3_en = 'At the temperature \\( \\vartheta_\\text{Ch}= \\SI{ 23 }{\\degreeCelsius} \\) the flow rate is'
+sectionResult3_TX_en = 'At the temperatures \\( \\vartheta_\\text{Ch}= \\SI{ 23 }{\\degreeCelsius} \\) and \\( \\vartheta_\\text{Ch}= \\SI{ 23 }{\\degreeCelsius} \\) the flow rates are'
+sectionResult4_en = 'The relative uncertainty \\(U\\) of the stated leak rate are    \\( \\SI{'+ LeakUncertainty +'}{\\percent} \\).'
+
+sectionResult_en = '\\section{' + sectionTitelResult_en + '}\n'  + sectionResult1_en 
+        
+
+        
+
+    
+sectionResult = '\\section{' + sectionTitelResult + '\\linebreak {\\small \\emph{' + sectionTitelResult_en + '}}}\n'    + sectionResult1         + '\\begin{english}' + sectionResult1_en   + '\\end{english} ' + tab_q_mol_Val + sectionResult2  + '\\begin{english}' + sectionResult2_en + '\\end{english} ' + q_pV_allg  + sectionResult3 + '\\begin{english}' + sectionResult3_en  + '\\end{english} ' +  tab_q_pV_Val + sectionResult4 + '\\begin{english}' + sectionResult4_en + '\\end{english} \n'
+sectionResult_en = sectionResult_en + sectionResult2_en  +   sectionResult4_en 
+
+
+
+
+    
+#######     4. Section: Uncertainty   ###################################
+
+sectionU1 = 'Angegeben ist die erweiterte Messunsicherheit \\(U\\), die sich aus der Standardmessunsicherheit durch Multiplikation mit dem Erweiterungsfaktor \\(k = 2\\)  ergibt. Sie wurde gemäß dem „Guide to the Expression of Uncertainty in Measurement (GUM)“ ermittelt. Der Wert der Messgröße liegt dann im Regelfall mit einer Wahrscheinlichkeit von annähernd \\SI{95}{\\percent} im zugeordneten Überdeckungsintervall.\n '
+sectionU1_en = 'The uncertainty \\(U\\) stated is the expanded measurement uncertainty obtained by multiplying the standard measurement uncertainty by the coverage factor \\(k = 2\\). It has been determined in accordance with the  “Guide to the Expression of Uncertainty in Measurement (GUM)”. The value of the measurand then normally lies, with a probability of approximately \\SI{95}{\\percent} within the attributed coverage interval.'
+
+sectionU = '\\section{' + sectionTitelUncertainty + '\\linebreak {\\small \\emph{' + sectionTitelUncertainty_en + '}}}\n' + sectionU1 + '\\begin{english}' + sectionU1_en + '\\end{english} \n'
+sectionU_en = '\\section{' + sectionTitelUncertainty_en + '}\n' + sectionU1_en 
+
 
 
 if(lang!='en'):
-    print("de",lang)
-    with open(ks,'w', encoding='utf-8') as file:
+    print("Kalibrierschein in deutsch",lang)
     
+    with open(ks,'w', encoding='utf-8') as file:
+        
         file.write('\\listfiles\n')
         file.write('\\documentclass[de,KK,CMC]{kalibrierschein}\n ')
         file.write(obj)
@@ -284,47 +318,32 @@ if(lang!='en'):
         file.write('\\byOrder{Dr. M.Bernien}\n')
         file.write(examiner)
         file.write(certificateDate)
-    
-        file.write('\\begin{document}\n')
-    
-        file.write('\\printFirstPage\n')
-    
-        file.write(sectionTitleText_de)
-        sectionText = sectionTitleText_de
-    
-        file.write(sectionTitelProcedure_text)
-        file.write(sectionProcedure_text)
-        file.write('\\pagebreak')
-        file.write(sectionTitelMeasurement_text)
-        
         
-        if(TemperatureTLx!=23):
-            file.write(sectionResult_Tx)
-            print("nicht 23")
-
-        else:
-            file.write(sectionResult)
-            print(" 23 ToDo", sectionResult)
-            
-          
-            
-            
-        file.write('\\section{Unsicherheit \\linebreak {\\small \\emph{Uncertainty of Calibration}}} ')
-        file.write(sectionU_text)
-    
-        file.write('\\printLastPage')
-        file.write('\\end{document}\\n')
+        file.write('\\begin{document}\n')
         
+        file.write('\\printFirstPage\n')
+        file.write(sectionDiscription)
         
         
         
+        file.write(sectionProcedure)
+        file.write('\\pagebreak ')
+        file.write(sectionResult)
+        file.write(sectionU)
         
         
         
+        file.write('\\pagebreak ')
+                
+        file.write('\\printLastPage')
+        file.write('\\end{document}\n')
+        print("bis hier funktioniert")
 else:
-    print("en Kal",lang)
-    with open(ks,'w', encoding='utf-8') as file:
+    print('"Kalibrierschein in ',lang, "en")
     
+
+    with open(ks,'w', encoding='utf-8') as file:
+        
         file.write('\\listfiles\n')
         file.write('\\documentclass[en,KK,CMC]{kalibrierschein}\n ')
         file.write(obj)
@@ -338,48 +357,49 @@ else:
         file.write('\\byOrder{Dr. M.Bernien}\n')
         file.write(examiner)
         file.write(certificateDate)
-    
+        
         file.write('\\begin{document}\n')
-    
+        
         file.write('\\printFirstPage\n')
-    
-        file.write(sectionTitleText_en)
-        sectionText = sectionTitleText_en
-    
-        file.write(sectionTitelProcedure_text_en)
-        file.write(sectionProcedure_text_en)
+        file.write(sectionDiscription_en)
         
-        file.write(sectionTitelMeasurement_text_en)
-        file.write(sectionResult_en)
-        file.write(sectionResultU_en)
         
-        if(TemperatureTLx == 23):
-            file.write(sectionResult_Tx)
-            print("nicht 23",TemperatureTLx)
-
-        else:
-            
-            print(" 23 ToDo")
         
-        #file.write(sectionTitelUncertainty_text_en)
-        #file.write(sectionU_text_en)
-    
-        file.write('\\printLastPage')
-        file.write('\\end{document}')
+        file.write(sectionProcedure_en)
+        file.write(sectionResult_en)
+        file.write(sectionU_en)
         
         
+        
+        file.write('\\pagebreak ')
+                
+        file.write('\\printLastPage')
+        file.write('\\end{document}\n')
+        print("bis hier funktioniert")
+
+
+ ####################Erstellung des cer-Dokuments ##########################
+ 
 
  
+ ##### Doukument "cer" wird erstellt#######
+ 
+
+MeasurementDateBegin = doc_cal["Calibration"]["Measurement"]["Date"][0]["Value"]
+MeasurementDateBegin = MeasurementDateBegin[0]
+MeasurementDateEnd = doc_cal["Calibration"]["Measurement"]["Date"][0]["Value"]
+MeasurementDateEnd = MeasurementDateEnd[0]
+DeviceClass= "TLA"
+
+
 doc_cer["Certificate"]={"Meta":{"std": ["FM1"],
                                  "id":[id_], 
                                  "kind" :[kind], 
                                  "gas": [gas], 
                                  "lang":lang,
-                                 "calibration_type":calibration_type,
-                                 }}
-
-
-
+                                 "calibration_type":calibration_type, 
+                                 "last_cert":last_cert}}
+     
 doc_cer["Certificate"]["Titlepage"]={"CertificateDate" :CertificateDate, 
                                      "FullYear": "2024",
                                      "ShortYear": "24",
@@ -406,30 +426,38 @@ doc_cer["Certificate"]["Titlepage"]={"CertificateDate" :CertificateDate,
                                  "ByOrder": ByOrder,
                                   } 
 
-
-
-
-
-doc_cer["Certificate"]["Section"]= [{"Heading": "Description relating to calibration device","Paragraph":sectionText},
-                                    {"Heading": "Calibration procedure","Paragraph":sectionProcedure_text},
+if(lang!='en'):
+    doc_cer["Certificate"]["Section"]= [{"Heading": "Description relating to calibration device","Paragraph":sectionDiscription},
+                                    {"Heading": "Calibration procedure","Paragraph":sectionProcedure},
                                     {"Heading": "Measurement results","Paragraph":sectionResult},
                                     {"Heading": "Uncertainty of Calibration","Paragraph":sectionU}],
 
+else:
+      doc_cer["Certificate"]["Section"]= [{"Heading": "Description relating to calibration device","Paragraph":sectionDiscription_en},
+                                      {"Heading": "Calibration procedure","Paragraph":sectionProcedure_en},
+                                      {"Heading": "Measurement results","Paragraph":sectionResult_en},
+                                      {"Heading": "Uncertainty of Calibration","Paragraph":sectionU_en}],  
+
 doc_cer["Certificate"]["Formula"]={"NoOfMeasurements": NoOfMeasurements,
                                 "FlowMol": FlowMol,
-                                "FlowpV23": FlowpV23,
+                                "FlowpV23":FlowpV23,
                                 "FlowpV2X":FlowpV2X,
-                                "Gauge": Gauge,
                                 "TemperatureTL": TemperatureTL,
                                 "TemperatureTLx": TemperatureTLx,
-                                "LeakUncertainty": LeakUncertainty,
-                                "MeasurementDate": MeasurementDate,
-                                "QMS": QMS,
-                                
+                                "LeakUncertainty": LeakUncertainty
                                 } 
+
+
+                                  
+                           
+ #
+ #
+
 db.save(doc_cer)
 
 
 
 
 
+
+ 
\ No newline at end of file