// This is an object that contains all elements and their parameters
// To replace all other functions 
const elemPars = {
    muon : {
	Z :  1 ,
	A :  0.1134289259 ,
	rho : 0 ,
	Elast : 0 ,
	ICRU : [] , 
	IAEA : [] 
    },
    "Li-8" : {
	Z :  3 ,
	A :  8.02248624 ,
	rho : 0 ,
	Elast : 0 ,
	ICRU : [] , 
	IAEA : [] 
    },
    "B-12" : {
	Z :  5 ,
	A :  12.0143526 ,
	rho : 0 ,
	Elast : 0 ,
	ICRU : [] , 
	IAEA : [] 
    },
    "Mg-31" : {
	Z :  12 ,
	A :  30.996648 ,
	rho : 0 ,
	Elast : 0 ,
	ICRU : [] , 
	IAEA : [] 
    },
    H : {
	Z :  1 ,
	A :  1.008 ,
	rho : 0.08 ,
	Elast : 0.1 ,
	ICRU : [1.25400,1.44000,242.60001,12000.00000,0.11590], 
	IAEA : [1.21941306,1.39705253,316.72610292,3622.08960714,0.03609996]
    },
    He : {
	Z :  2 ,
	A :  4.003 ,
	rho : 0.12 ,
	Elast : 0.1 ,
	ICRU : [1.22900,1.39700,484.50000,5873.00000,0.05225] , 
	IAEA : [] 
    },
    Li : {
	Z :  3 ,
	A :  6.939 ,
	rho : 0.53 ,
	Elast : 1.63 ,
	ICRU : [1.41100,1.60000,725.59998,3013.00000,0.04578] , 
	IAEA : [2.55867734,2.98398784,672.22623329,223.63937274,0.05756479]
    },    
    Be : {
	Z :  4 ,
	A :  9.012 ,
	rho : 1.85 ,
	Elast : 3.32 ,
	ICRU : [2.24800,2.59000,966.00000,153.80000,0.03475] , 
	IAEA : [2.13846776,2.43024550,1353.80005691,500.78353377,0.01143076] 
    },    
    B : {
	Z :  5 ,
	A :  10.811 ,
	rho : 2.34 ,
	Elast : 5.77 ,
	ICRU : [2.47400,2.81500,1206.00000,1060.00000,0.02855] , 
	IAEA : [2.92598306,3.33271910,1523.83401267,574.31712932,0.01671298]
    },    
    C : {
	Z :  6 ,
	A :  12.011 ,
	rho : 2.26 ,
	Elast : 7.37 ,
	ICRU : [2.60100,2.60100,1701.00000,1279.00000,0.01638] , 
	IAEA : [2.51057212,2.84874359,1325.63086028,2111.57332043,0.03815981] 
    },    
    N : {
	Z :  7 ,
	A :  14.007 ,
	rho : 1.03 ,
	Elast : 4.92 ,
	ICRU : [2.95400,3.35000,1683.00000,1900.00000,0.02513] , 
	IAEA : [3.03231463,3.44621744,1287.27189959,3445.25706665,0.06909550] 
    },    
    O : {
	Z :  8 ,
	A :  15.999 ,
	rho : 2 ,
	Elast : 2.6 ,
	ICRU : [2.65200,3.00000,1920.00000,2000.00000,0.02230] , 
	IAEA : [2.58218404,2.91913321,2066.69556610,1937.28839450,0.01708201] 
    },    
    F : {
	Z :  9 ,
	A :  18.998 ,
	rho : 1.11 ,
	Elast : 0.84 ,
	ICRU : [2.08500,2.35200,2157.00000,2634.00000,0.01816] , 
	IAEA : [] 
    },    
    Ne : {
	Z :  10 ,
	A :  20.183 ,
	rho : 1.5 ,
	Elast : 0.02 ,
	ICRU : [1.95100,2.19900,2393.00000,2699.00000,0.01568] , 
	IAEA : [] 
    },    
    Na : {
	Z :  11 ,
	A :  22.99 ,
	rho : 0.97 ,
	Elast : 1.11 ,
	ICRU : [2.54200,2.86900,2628.00000,1854.00000,0.01472] , 
	IAEA : [] 
    },    
    Mg : {
	Z :  12 ,
	A :  24.312 ,
	rho : 1.74 ,
	Elast : 1.51 ,
	ICRU : [3.79100,4.29300,2862.00000,1009.00000,0.01397] , 
	IAEA : [4.32219620,4.95332934,2711.05757349,99.32422512,0.01692829] 
    },    
    Al : {
	Z :  13 ,
	A :  26.982 ,
	rho : 2.7 ,
	Elast : 3.39 ,
	ICRU : [4.15400,4.73900,2766.00000,164.50000,0.02023] , 
	IAEA : [4.16266645,4.73942640,3007.21967155,192.15430476,0.01478852] 
    },    
    Si : {
	Z :  14 ,
	A :  28.086 ,
	rho : 2.33 ,
	Elast : 4.63 ,
	ICRU : [4.91400,5.59800,3193.00000,232.70000,0.01419] , 
	IAEA : [4.56277193,5.17964542,3812.93366288,249.45105835,0.00951865]
    },
    P : {
	Z :  15 ,
	A :  30.974 ,
	rho : 1 ,
	Elast : 3.43 ,
	ICRU : [3.23200,3.64700,3561.00000,1560.00000,0.01267] , 
	IAEA : [] 
    },    
    S : {
	Z :  16 ,
	A :  32.064 ,
	rho : 2.07 ,
	Elast : 2.85 ,
	ICRU : [3.44700,3.89100,3792.00000,1219.00000,0.01211] , 
	IAEA : [] 
    },    
    Cl : {
	Z :  17 ,
	A :  35.453 ,
	rho : 2.03 ,
	Elast : 1.4 ,
	ICRU : [5.30100,6.00800,3969.00000,645.09998,0.01183] , 
	IAEA : [5.18954121,5.87010049,5726.20198003,338.90592713,0.00527894] 
    },    
    Ar : {
	Z :  18 ,
	A :  39.948 ,
	rho : 1.77 ,
	Elast : 0.08 ,
	ICRU : [5.73100,6.50000,4253.00000,530.00000,0.01123] , 
	IAEA : [] 
    },    
    K : {
	Z :  19 ,
	A :  39.102 ,
	rho : 0.86 ,
	Elast : 0.93 ,
	ICRU : [5.15200,5.83300,4482.00000,545.70001,0.01129] , 
	IAEA : [] 
    },    
    Ca : {
	Z :  20 ,
	A :  40.08 ,
	rho : 1.55 ,
	Elast : 1.84 ,
	ICRU : [5.52100,6.25200,4710.00000,553.29999,0.01120] , 
	IAEA : [7.38419020,8.41800474,4257.94547049,311.84732092,0.01482602] 
    },    
    Sc : {
	Z :  21 ,
	A :  44.956 ,
	rho : 2.99 ,
	Elast : 3.9 ,
	ICRU : [5.20100,5.88400,4938.00000,560.90002,0.01000] , 
	IAEA : [6.27366940,7.11486087,5202.32117316,349.64931132,0.00808596] 
    },    
    Ti : {
	Z :  22 ,
	A :  47.9 ,
	rho : 4.54 ,
	Elast : 4.85 ,
	ICRU : [4.85800,5.48900,5260.00000,651.09998,0.00893] , 
	IAEA : [4.89215322,5.52996090,4733.05002706,821.54929980,0.01141794] 
    },
    V : {
	Z :  23 ,
	A :  50.942 ,
	rho : 6.11 ,
	Elast : 5.31 ,
	ICRU : [4.47900,5.05500,5391.00000,952.29999,0.00912] , 
	IAEA : [4.39418898,4.95984106,5216.28902299,873.00768319,0.00982301]
    },
    Cr : {
	Z :  24 ,
	A :  51.996 ,
	rho : 7.19 ,
	Elast : 4.1 ,
	ICRU : [3.98300,4.48900,5616.00000,1336.00000,0.00841] , 
	IAEA : [4.22355616,4.76724205,4805.40719904,1062.25237873,0.01508696] 
    },
    Mn : {
	Z :  25 ,
	A :  54.938 ,
	rho : 7.43 ,
	Elast : 2.92 ,
	ICRU : [3.46900,3.90700,5725.00000,1461.00000,0.00883] , 
	IAEA : [3.45870888,3.89580224,5452.18588822,1778.16054656,0.01057380] 
    },
    Fe : {
	Z :  26 ,
	A :  55.847 ,
	rho : 7.87 ,
	Elast : 4.28 ,
	ICRU : [3.51900,3.96300,6065.00000,1243.00000,0.00778] , 
	IAEA : [3.69846643,4.16916938,5392.90710239,1040.38447053,0.01152298] 
    },
    Co : {
	Z :  27 ,
	A :  58.933 ,
	rho : 8.9 ,
	Elast : 4.39 ,
	ICRU : [3.14000,3.53500,6288.00000,1372.00000,0.00736] , 
	IAEA : [3.55890909,4.00775461,6796.04145497,933.86447935,0.00558368] 
    },
    Ni : {
	Z :  28 ,
	A :  58.71 ,
	rho : 8.9 ,
	Elast : 4.44 ,
	ICRU : [3.55300,4.00400,6205.00000,555.09998,0.00876] , 
	IAEA : [3.42262695,3.86234880,4759.65515188,520.18934465,0.02026669] 
    },
    Cu : {
	Z :  29 ,
	A :  63.54 ,
	rho : 8.96 ,
	Elast : 3.49 ,
	ICRU : [3.69600,4.19400,4649.00000,81.13000,0.02242] , 
	IAEA : [3.54912421,4.02142201,4344.22605325,128.32905834,0.02886218] 
    },
    Zn : {
	Z :  30 ,
	A :  65.37 ,
	rho : 7.13 ,
	Elast : 1.35 ,
	ICRU : [4.21000,4.75000,6953.00000,295.20001,0.00681] , 
	IAEA : [4.31895518,4.91763977,5346.03925560,46.16548699,0.01518164] 
    },
    Ga : {
	Z :  31 ,
	A :  69.72 ,
	rho : 5.91 ,
	Elast : 2.81 ,
	ICRU : [5.04100,5.69700,7137.00000,202.60001,0.00673] , 
	IAEA : [4.11015447,4.63998531,7681.41419449,149.38563152,0.00628772] 
    },
    Ge : {
	Z :  32 ,
	A :  72.59 ,
	rho : 5.32 ,
	Elast : 3.85 ,
	ICRU : [5.55400,6.30000,6496.00000,110.00000,0.00969] , 
	IAEA : [5.80984815,6.60667983,6039.04808738,87.19744473,0.01158192] 
    },
    As : {
	Z :  33 ,
	A :  74.922 ,
	rho : 5.72 ,
	Elast : 2.96 ,
	ICRU : [5.32300,6.01200,7611.00000,292.50000,0.00645] , 
	IAEA : [] 
    },
    Se : {
	Z :  34 ,
	A :  78.96 ,
	rho : 4.79 ,
	Elast : 2.25 ,
	ICRU : [5.87400,6.65600,7395.00000,117.50000,0.00768] , 
	IAEA : [5.58734301,6.31119973,8423.01872583,221.61559131,0.00530434] 
    },
    Br : {
	Z :  35 ,
	A :  79.909 ,
	rho : 3.14 ,
	Elast : 1.22 ,
	ICRU : [6.65800,7.53600,7694.00000,222.30000,0.00651] , 
	IAEA : [6.28480648,7.09489448,11732.76411988,150.96205589,0.00281298] 
    },
    Kr : {
	Z :  36 ,
	A :  83.8 ,
	rho : 3.1 ,
	Elast : 0.12 ,
	ICRU : [6.41300,7.24000,11850.00000,153.70000,0.00288] , 
	IAEA : [6.47378266,7.31581518,9199.06183849,216.98680923,0.00437111] 
    },
    Rb : {
	Z :  37 ,
	A :  85.47 ,
	rho : 1.53 ,
	Elast : 0.85 ,
	ICRU : [5.69400,6.42900,8478.00000,292.89999,0.00609] , 
	IAEA : [8.48759187,9.62951209,7271.11124671,272.67996745,0.00818815] 
    },
    Sr : {
	Z :  38 ,
	A :  87.62 ,
	rho : 2.54 ,
	Elast : 1.72 ,
	ICRU : [6.33900,7.15900,8693.00000,330.29999,0.00600] , 
	IAEA : [8.66447838,9.84912713,5979.31960977,334.15705556,0.01184544] 
    },
    Y : {
	Z :  39 ,
	A :  88.905 ,
	rho : 4.47 ,
	Elast : 4.37 ,
	ICRU : [6.40700,7.23400,8907.00000,367.79999,0.00589] , 
	IAEA : [7.54854264,8.54789357,6885.34110669,429.53252110,0.00930644] 
    },
    Zr : {
	Z :  40 ,
	A :  91.22 ,
	rho : 6.51 ,
	Elast : 6.25 ,
	ICRU : [6.73400,7.60300,9120.00000,405.20001,0.00576] , 
	IAEA : [6.24168401,7.04236496,10674.06252597,269.66181445,0.00339805] 
    },
    Nb : {
	Z :  41 ,
	A :  92.906 ,
	rho : 8.57 ,
	Elast : 7.57 ,
	ICRU : [6.90100,7.79100,9333.00000,442.70001,0.00559] , 
	IAEA : [5.96194954,6.72632300,10250.57513827,275.25886405,0.00386599] 
    },
    Mo : {
	Z :  42 ,
	A :  95.94 ,
	rho : 10.22 ,
	Elast : 6.82 ,
	ICRU : [6.42400,7.24800,9545.00000,480.20001,0.00538] , 
	IAEA : [5.58867862,6.29983727,9573.16605660,523.57577519,0.00473082] 
    },
    Tc : {
	Z :  43 ,
	A :  98 ,
	rho : 11.5 ,
	Elast : 6.85 ,
	ICRU : [6.79900,7.67100,9756.00000,517.59998,0.00532] , 
	IAEA : [] 
    },
    Ru : {
	Z :  44 ,
	A :  101.07 ,
	rho : 12.37 ,
	Elast : 6.74 ,
	ICRU : [6.10900,6.88700,9966.00000,555.09998,0.00515] , 
	IAEA : [] 
    },
    Rh : {
	Z :  45 ,
	A :  102.905 ,
	rho : 12.41 ,
	Elast : 5.75 ,
	ICRU : [5.92400,6.67700,10180.00000,592.50000,0.00492] , 
	IAEA : [] 
    },
    Pd : {
	Z :  46 ,
	A :  106.4 ,
	rho : 12.02 ,
	Elast : 3.89 ,
	ICRU : [5.23800,5.90000,10380.00000,630.00000,0.00476] , 
	IAEA : [4.74762031,5.34871025,8086.17802763,942.05721488,0.00842671]
    },
    Ag : {
	Z :  47 ,
	A :  107.87 ,
	rho : 10.5 ,
	Elast : 2.95 ,
	ICRU : [5.34500,6.03800,6790.00000,397.79999,0.01676] , 
	IAEA : [5.42052240,6.17824432,4642.18214950,90.75350922,0.06061521] 
    },
    Cd : {
	Z :  48 ,
	A :  112.4 ,
	rho : 8.65 ,
	Elast : 1.16 ,
	ICRU : [5.81400,6.55400,10800.00000,355.50000,0.00463] , 
	IAEA : [4.89128643,5.50754704,11831.77188508,396.06905848,0.00412049] 
    },
    In : {
	Z :  49 ,
	A :  114.82 ,
	rho : 7.31 ,
	Elast : 2.52 ,
	ICRU : [6.22900,7.02400,11010.00000,370.89999,0.00454] , 
	IAEA : [5.98978289,6.77050040,6343.54720062,564.65410792,0.02270520] 
    },
    Sn : {
	Z :  50 ,
	A :  118.69 ,
	rho : 7.31 ,
	Elast : 3.14 ,
	ICRU : [6.40900,7.22700,11210.00000,386.39999,0.00447] , 
	IAEA : [6.73191335,7.61854414,6946.18830598,347.19391310,0.01677246] 
    },
    Sb : {
	Z :  51 ,
	A :  121.75 ,
	rho : 6.68 ,
	Elast : 2.75 ,
	ICRU : [7.50000,8.48000,8608.00000,348.00000,0.00907] , 
	IAEA : [7.92400389,8.99628409,5736.29881090,403.11722206,0.02973016] 
    },
    Te : {
	Z :  52 ,
	A :  127.6 ,
	rho : 6.24 ,
	Elast : 2.23 ,
	ICRU : [6.97900,7.87100,11620.00000,392.39999,0.00440] , 
	IAEA : [] 
    },
    I : {
	Z :  53 ,
	A :  126.904 ,
	rho : 4.93 ,
	Elast : 1.11 ,
	ICRU : [7.72500,8.71600,11830.00000,394.79999,0.00438] , 
	IAEA : [] 
    },
    Xe : {
	Z :  54 ,
	A :  131.3 ,
	rho : 3.8 ,
	Elast : 0.16 ,
	ICRU : [8.33700,9.42500,10510.00000,269.60001,0.00621] , 
	IAEA : [8.96826400,10.16224223,8543.27304860,283.90067433,0.01019984] 
    },
    Cs : {
	Z :  55 ,
	A :  132.905 ,
	rho : 1.9 ,
	Elast : 0.8 ,
	ICRU : [7.28700,8.21800,12230.00000,399.70001,0.00445] , 
	IAEA : [] 
    },
    Ba : {
	Z :  56 ,
	A :  137.34 ,
	rho : 3.59 ,
	Elast : 1.9 ,
	ICRU : [7.89900,8.91100,12430.00000,402.10001,0.00451] , 
	IAEA : [] 
    },
    La : {
	Z :  57 ,
	A :  138.91 ,
	rho : 6.15 ,
	Elast : 4.47 ,
	ICRU : [8.04100,9.07100,12630.00000,404.50000,0.00454] , 
	IAEA : [8.16949326,9.21144395,13933.96869212,429.99442382,0.00347440] 
    },
    Ce : {
	Z :  58 ,
	A :  140.12 ,
	rho : 6.77 ,
	Elast : 4.32 ,
	ICRU : [7.48800,8.44400,12830.00000,406.89999,0.00442] , 
	IAEA : [] 
    },
    Pr : {
	Z :  59 ,
	A :  140.907 ,
	rho : 6.77 ,
	Elast : 3.7 ,
	ICRU : [7.29100,8.21900,13030.00000,409.29999,0.00430] , 
	IAEA : [] 
    },
    Nd : {
	Z :  60 ,
	A :  144.24001 ,
	rho : 7.01 ,
	Elast : 3.4 ,
	ICRU : [7.09800,8.00000,13230.00000,411.79999,0.00418] , 
	IAEA : [8.60801371,10.26060598,6798.65217629,7.06731816,0.02713704] 
    },
    Pm : {
	Z :  61 ,
	A :  147 ,
	rho : 7.22 ,
	Elast : 0.1 ,
	ICRU : [6.90900,7.78600,13430.00000,414.20001,0.00406] , 
	IAEA : [] 
    },
    Sm : {
	Z :  62 ,
	A :  150.35001 ,
	rho : 7.52 ,
	Elast : 2.14 ,
	ICRU : [6.72800,7.58000,13620.00000,416.60001,0.00398] , 
	IAEA : [] 
    },
    Eu : {
	Z :  63 ,
	A :  151.96001 ,
	rho : 5.24 ,
	Elast : 1.86 ,
	ICRU : [6.55100,7.38000,13820.00000,419.00000,0.00388] , 
	IAEA : [] 
    },
    Gd : {
	Z :  64 ,
	A :  157.25 ,
	rho : 7.9 ,
	Elast : 4.14 ,
	ICRU : [6.73900,7.59200,14020.00000,421.39999,0.00386] , 
	IAEA : [8.38379061,9.50012183,10804.38767518,110.71066098,0.00761735] 
    },
    Tb : {
	Z :  65 ,
	A :  158.924 ,
	rho : 8.23 ,
	Elast : 4.05 ,
	ICRU : [6.21200,6.99600,14210.00000,423.89999,0.00372] , 
	IAEA : [8.69907359,10.36476708,5985.09307671,7.76175759,0.04237031] 
    },
    Dy : {
	Z :  66 ,
	A :  162.5 ,
	rho : 8.55 ,
	Elast : 3.04 ,
	ICRU : [5.51700,6.21000,14400.00000,426.29999,0.00363] , 
	IAEA : [6.69350026,7.81543484,5289.65107666,12.11560717,0.05746489] 
    },
    Ho : {
	Z :  67 ,
	A :  164.92999 ,
	rho : 8.8 ,
	Elast : 3.14 ,
	ICRU : [5.22000,5.87400,14600.00000,428.70001,0.00350] , 
	IAEA : [] 
    },
    Er : {
	Z :  68 ,
	A :  167.25999 ,
	rho : 9.07 ,
	Elast : 3.29 ,
	ICRU : [5.07100,5.70600,14790.00000,433.00000,0.00341] , 
	IAEA : [4.31497049,4.85346547,12995.54504003,691.00380321,0.00499022] 
    },
    Tm : {
	Z :  69 ,
	A :  168.93401 ,
	rho : 9.32 ,
	Elast : 2.42 ,
	ICRU : [4.92600,5.54200,14980.00000,433.50000,0.00334] , 
	IAEA : [] 
    },
    Yb : {
	Z :  70 ,
	A :  173.03999 ,
	rho : 6.9 ,
	Elast : 1.6 ,
	ICRU : [4.78800,5.38600,15170.00000,435.89999,0.00329] , 
	IAEA : [6.38304258,7.21491284,12327.74719685,82.30064162,0.00516845] 
    },
    Lu : {
	Z :  71 ,
	A :  174.97 ,
	rho : 9.84 ,
	Elast : 4.43 ,
	ICRU : [4.89300,5.50500,15360.00000,438.29999,0.00324] , 
	IAEA : [7.00205766,8.09268611,4589.67801229,31.06321362,0.11142124] 
    },
    Hf : {
	Z :  72 ,
	A :  178.49001 ,
	rho : 13.31 ,
	Elast : 6.44 ,
	ICRU : [5.02800,5.65700,15550.00000,440.79999,0.00320] , 
	IAEA : [5.32763157,6.00140558,13853.49562768,206.93150053,0.00411522] 
    },
    Ta : {
	Z :  73 ,
	A :  180.948 ,
	rho : 16.65 ,
	Elast : 8.1 ,
	ICRU : [4.73800,5.32900,15740.00000,443.20001,0.00319] , 
	IAEA : [5.15280708,5.80545310,12417.25115167,231.48549646,0.00530723] 
    },
    W : {
	Z :  74 ,
	A :  183.85001 ,
	rho : 19.35 ,
	Elast : 8.9 ,
	ICRU : [4.58700,5.16000,15410.00000,415.29999,0.00341] , 
	IAEA : [4.81261962,5.41579909,15245.84079976,286.09077182,0.00344862] 
    },
    Re : {
	Z :  75 ,
	A :  186.2 ,
	rho : 21.04 ,
	Elast : 8.03 ,
	ICRU : [5.20100,5.85100,16120.00000,441.60001,0.00312] , 
	IAEA : [4.26021967,4.80273372,3191.05524918,76051.48730893,0.00003161] 
    },
    Os : {
	Z :  76 ,
	A :  190.2 ,
	rho : 22.6 ,
	Elast : 8.17 ,
	ICRU : [5.07100,5.70400,16300.00000,440.89999,0.00308] , 
	IAEA : [] 
    },
    Ir : {
	Z :  77 ,
	A :  192.2 ,
	rho : 22.4 ,
	Elast : 6.94 ,
	ICRU : [4.94600,5.56300,16490.00000,440.10001,0.00296] , 
	IAEA : [4.16543126,4.68849191,6887.94139926,4263.90641919,0.00000004] 
    },
    Pt : {
	Z :  78 ,
	A :  195.09 ,
	rho : 21.45 ,
	Elast : 5.84 ,
	ICRU : [4.47700,5.03400,16670.00000,439.29999,0.00287] , 
	IAEA : [4.62228847,5.20033612,16308.49878855,266.02263275,0.00309560] 
    },
    Au : {
	Z :  79 ,
	A :  196.967 ,
	rho : 19.32 ,
	Elast : 3.81 ,
	ICRU : [4.84400,5.45800,7852.00000,975.79999,0.02077] , 
	IAEA : [4.84253074,5.44769072,15602.21662947,412.25485588,0.00331383]
    },
    Hg : {
	Z :  80 ,
	A :  200.59 ,
	rho : 13.55 ,
	Elast : 0.67 ,
	ICRU : [4.30700,4.84300,17040.00000,487.79999,0.00288] , 
	IAEA : [] 
    },
    Tl : {
	Z :  81 ,
	A :  204.37 ,
	rho : 11.85 ,
	Elast : 1.88 ,
	ICRU : [4.72300,5.31100,17220.00000,537.00000,0.00291] , 
	IAEA : [] 
    },
    Pb : {
	Z :  82 ,
	A :  207.19 ,
	rho : 11.35 ,
	Elast : 2.03 ,
	ICRU : [5.31900,5.98200,17400.00000,586.29999,0.00287] , 
	IAEA : [9.42473604,17.46235676,11946.86905435,0.00000001,0.00652912] 
    },
    Bi : {
	Z :  83 ,
	A :  208.98 ,
	rho : 9.75 ,
	Elast : 2.18 ,
	ICRU : [5.95600,6.70000,17800.00000,677.00000,0.00266] , 
	IAEA : [10.25823796,12.26670424,7765.05387481,7.37274504,0.02310050] 
    },
    Po : {
	Z :  84 ,
	A :  210 ,
	rho : 9.3 ,
	Elast : 1.5 ,
	ICRU : [6.15800,6.92800,17770.00000,586.29999,0.00281] , 
	IAEA : [] 
    },
    At : {
	Z :  85 ,
	A :  210 ,
	rho : 0 ,
	Elast : 0.1 ,
	ICRU : [6.20300,6.97900,17950.00000,586.29999,0.00278] , 
	IAEA : [] 
    },
    Rn : {
	Z :  86 ,
	A :  222 ,
	rho : 0 ,
	Elast : 0.2 ,
	ICRU : [6.18100,6.95400,18120.00000,586.29999,0.00275] , 
	IAEA : [] 
    },
    Fr : {
	Z :  87 ,
	A :  223 ,
	rho : 0 ,
	Elast : 0.1 ,
	ICRU : [6.94900,7.82000,18300.00000,586.29999,0.00274] , 
	IAEA : [] 
    },
    Ra : {
	Z :  88 ,
	A :  226 ,
	rho : 0 ,
	Elast : 1.66 ,
	ICRU : [7.50600,8.44800,18480.00000,586.29999,0.00273] , 
	IAEA : [] 
    },
    Ac : {
	Z :  89 ,
	A :  227 ,
	rho : 0 ,
	Elast : 4.25 ,
	ICRU : [7.64800,8.60900,18660.00000,586.29999,0.00270] , 
	IAEA : [] 
    },
    Th : {
	Z :  90 ,
	A :  232.03799 ,
	rho : 11.72 ,
	Elast : 6.2 ,
	ICRU : [7.71100,8.67900,18830.00000,586.29999,0.00264] , 
	IAEA : [] 
    },
    Pa : {
	Z :  91 ,
	A :  231 ,
	rho : 15.4 ,
	Elast : 0.1 ,
	ICRU : [7.40700,8.33600,19010.00000,586.29999,0.00260] , 
	IAEA : [] 
    },
    U : {
	Z :  92 ,
	A :  238.03 ,
	rho : 18.95 ,
	Elast : 5.55 ,
	ICRU : [7.29000,8.20400,19180.00000,586.29999,0.00267] , 
	IAEA : [] 
    },
    "" : {
	Z :  0 ,
	A :  0.0 ,
	rho : 0 ,
	Elast : 0 ,
	ICRU : [0,0,0,0,0] , 
	IAEA : [] 
    }
};

// Extra densities 
var rhos = {
    "NbN":8.47,
    "Bi2Se3":7.51,
    "La2CuO4": 7.08,
    "La1.84Sr0.16CuO4": 6.94,
    "N2":1.145,
    "ZnO":5.61,
    "ZnSe":5.26,
    "ZnS":4.09,
    "ZrO":6.0,
    "Gd3Ga5O12":7.08,
    "MgAl2O4":3.60,
    "NdGaO3":7.57,
    "YAlO3":4.88,
    "Y3Al5O12":4.55,
    "LiF":2.60,
    "CaF2":3.18,
    "BaFe":4.83,
    "MgF2":3.18,
    "SiO2":2.65,
    "TiO2":4.26,
    "KTaO3":6.967,
    "LaAlO3":6.70,
    "Al2O3":3.98,
    "SrTiO3":5.12,
    "SrLaGaO4":6.389,
    "SrLaAlO4":5.924,
    "NbSe2":6.30,
    "MgO":3.58,
    "YBa2Cu3O7":6.54,
    "GaAs":5.32,
    "C60":1.65
}

// This file contains function that are generic Javascript for TrimSP

function parse_formula (mf) {
    // This function takes a chemical formula and returns
    // an object that contains the atoms and their number

    // replace all types of brackets into ()
    var mf = mf.replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")").replace(/\s+/g,"");
    if(/^\d+/.test(mf)) throw new SyntaxError("Molecular formula should not start with a number!");
    var mol = {};
    // go into brackets and collect info
    while(mf.includes("(")){
	var x = mf.lastIndexOf("(");
	var y = mf.indexOf(")", mf.lastIndexOf("("));
	
	var z = mf.substr(x+1, y-x-1);
	var c = mf.substr(y+1);
	c = /^\d+/.exec(c);
	c=(c!= null)?Number(c[0]):1;
	// recursive
	var a = this.parse_formula(z);
	var b = "";
	for(var k in a){
	    b+=k+""+a[k]*c;
	} 
	mf = mf.substr(0, x)+ b + mf.substr(y+1+((c>1)?(c+'').length:0));		
    }
		
    var m = "";
    // Separate element name from stoichiometry
    //    while(m = /([A-Z]{1}[a-z]{0,}[0-9]{0,})/.exec(mf)){
    while(m = /([A-Z]{1}[a-z]{0,}[0-9]{0,}\.?[0-9]{0,})/.exec(mf)){
	// Element
	var m1 = /([A-Z]{1,}[a-z]{0,})/.exec(m[0]);
	// Stoichiometry
	//var m2 = /\d+/.exec(m[0]);
	var m2 = /\d+\.?\d{0,}/.exec(m[0]);
	if(typeof mol[m1[0]] == 'undefined') mol[m1[0]]=(m2!=null)?Number(m2[0]):1;
	else mol[m1[0]] += (m2!=null)?Number(m2[0]):1;
	mf = mf.replace(m[0], "");
    }
    return mol;
}

function StoppingCoefficients(Element,flag)
{
    // flag = 1 prefer ICRU otherwise prefer IAEA

    // Updated Anderson-Ziegler table values for hydrogen projectiles using
    // up-to-date stopping data from the IAEA database (https://www-nds.iaea.org/stopping/).
    // For further details on their determination, see e.g.:
    // R. M. L. McFadden at al., arXiv:2212.11081 [cond-mat.supr-con]
    // https://doi.org/10.48550/arXiv.2212.11081

    if (flag || elemPars[Element].IAEA.length < 5) {
	// Using stopping coefficients derived from ICRU Report 49
	//return StoppingCoefficientsICRU[Element];
	return elemPars[Element].ICRU;
    } else {
	// Using stopping coefficients derived from data in the IAEA database;
	// however, if they are unavailable, return those from ICRU Report 49
	//return (Element in StoppingCoefficientsIAEA) ? StoppingCoefficientsIAEA[Element] : StoppingCoefficientsICRU[Element];
	return elemPars[Element].IAEA;
    }
}


function rho_fun()
{
    var irow = this.parentNode.parentNode.rowIndex;
    var caller = this.id;
    var chem = document.getElementById(caller).value;
    var rhoLi = "L"+irow+"rho";

    var rho = 0;
    
    if (elemPars[chem]) {
	rho = elemPars[chem].rho;
    } else {
	// Did not find density in elements list
	if (isFinite(rhos[chem])) {
	    // Found in densities list of compositions
	    rho = rhos[chem];
	} else {
	    // suggest a material density based on composition (when it's undefined)
            let layer_formula = parse_formula(chem);

            // determine the stoichiometry sum (for normalization)
            let stoichiometry_sum = 0;
	    for (key of Object.keys(layer_formula)) {
	        stoichiometry_sum = stoichiometry_sum + layer_formula[key];
	    }

	    // determine the density using on a weighted average of the elemental densities
	    let density_estimate = 0;
	    for (key of Object.keys(layer_formula)) {
	        if (layer_formula[key] != null) {
	            density_estimate = density_estimate + (layer_formula[key] / stoichiometry_sum) * elemPars[key].rho;
	        }
	    }

            rho = density_estimate;
	    alert("Warning: The density for this layer is only an estimate!")
	}
    }
    // Set value in appropriate cell
    document.getElementById(rhoLi).value = rho;    
}

function openTab(event, tabName) {
    // Declare all variables
    var i, tabcontent, tablinks;
    // Get all elements with class="tabcontent" and hide them
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
	tabcontent[i].style.display = "none";
    }

    // Get all elements with class="tablinks" and remove the class "active"
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
	tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    // Show the current tab, and add an "active" class to the button that opened the tab
    document.getElementById(tabName).style.display = "block";
    if (event) event.currentTarget.className += " active";
}

function adjust_table()
{
   var numLayer = document.getElementById("numLayer").value;
   var LTable = document.getElementById("LTable");
   var Nrows = LTable.rows.length;

   var Comps = [];
   var Rhos = [];
   var Ds = [];

// Need to loop to get the right number of rows when reloading
   if (numLayer >= Nrows) {
      for (i = Nrows;i<=numLayer;i++) {
          var row = LTable.insertRow(i);
          var Li = row.insertCell(0);
          Li.innerHTML = i;
          var compL = row.insertCell(1);
          var compCell = document.createElement("input");
          compCell.id = "L"+i+"Comp";
          compCell.name = "L"+i+"Comp";
          compCell.size = 15;
	  compCell.onchange = rho_fun;
	  if (Comps[i-1]) {compCell.value = Comps[i-1];}else{compCell.value = 'SrTiO3';}
          compL.appendChild(compCell);
          var rhoL = row.insertCell(2);
          var rhoCell = document.createElement("input");
          rhoCell.id = "L"+i+"rho";
          rhoCell.name = "L"+i+"rho";
	  rhoCell.size = 5;
          rhoL.appendChild(rhoCell);
	  if (Rhos[i-1]) {rhoCell.value = Rhos[i-1];}else{rhoCell.value = '5.12';}
          var thickL = row.insertCell(3);
          var thickCell = document.createElement("input");
          thickCell.id = "L"+i+"d";
          thickCell.name = "L"+i+"d";
	  thickCell.size = 7;
          thickL.appendChild(thickCell);
	  if (Ds[i-1]) {thickCell.value = Ds[i-1];}else{thickCell.value = '10000';}
       }
    } else {
      for (i = Nrows-1;i>numLayer;i--) {
          LTable.deleteRow(i);
      }
    }
}

function adjust_scans()
{
    // Deal with scans checkbox and type
    var scanSeq = document.getElementById("scanSeq").checked;
    var sender = document.getElementById("scanSeq");
    var scanType = document.getElementById("scanType").value;
    // consider only if scans checkbox is checked
    if (scanSeq) {
	// Which type of scan
	if (scanType == "scanLoop") {
	    ShowHide(1,'ScansTable');
	    ShowHide(0,'ScansLine');
	} else {
	    ShowHide(1,'ScansLine');
	    ShowHide(0,'ScansTable');
	}
    } else {
	// Hide both
	    ShowHide(0,'ScansTable');
	    ShowHide(0,'ScansLine');
    }
}

function ProjSmartDefaults()
{
   var Proj = document.getElementById("ProjType").value;
   var sigEnergy = document.getElementById("sigEnergy");
   var sigAngle = document.getElementById("sigAngle");

   if (Proj == "muon") {
      sigEnergy.value = "450";
      sigAngle.value = "15";
   } else {
      sigEnergy.value = "0";
      sigAngle.value = "0";
   }      
}

function ProjNumberLimit()
{
   var numberProj = document.getElementById("numberProj").value;

   if (numberProj > 5000) {
       alert("Maximum number is 5000");
       document.getElementById("numberProj").value = 5000;
   }      
}


function ShowHide(onoff,item) {
// this function can switch item to visible/hidden onoff=1/0
    if(onoff){
//       document.getElementById(item).style.display = 'block';
       document.getElementById(item).style.visibility = "visible";
    } else {
//       document.getElementById(item).style.display = 'none';
       document.getElementById(item).style.visibility = "hidden";
    }
}

function prep_cfg(toggle) {
    // This function collects various values and returns
    // toggle=1  : returns object with all values
    // toggle!=1 : returns string containing cfg file
    let TrimSPcfg = "";
    let strtmp = "";
    let valtmp = "";

    let All = new Object();
    All['trimPath']=document.getElementById("trimPath").value;
    
    // Prepare Layers section
    let LayersSec = "[Layers]\n";
    let numLayer = document.getElementById("numLayer").value;
    All['numLayer']=numLayer;
    LayersSec = LayersSec + "numLayer="+numLayer+"\n";
    for (i = 1;i<=numLayer;i++) {
	strtmp = "L"+i+"Comp";
	valtmp = document.getElementById(strtmp).value;
	All[strtmp]=valtmp;
	LayersSec = LayersSec + strtmp +"="+ valtmp+"\n";
	strtmp = "L"+i+"rho";
	valtmp = document.getElementById(strtmp).value;
	All[strtmp]=valtmp;
	LayersSec = LayersSec + strtmp +"="+ valtmp+"\n";
	strtmp = "L"+i+"d";
	valtmp = document.getElementById(strtmp).value;
	All[strtmp]=valtmp;
	LayersSec = LayersSec + strtmp +"="+ valtmp+"\n";
    }

    // Prepare projectile parameters section
    let parProj = ["workPath","fileNamePrefix","ProjType","numberProj","z0","dz","valEnergy","sigEnergy","valAngle","sigAngle","ranSeed"];
    let ProjSec = "[ProjectileParameters]\n";
    for (key of parProj) {
	All[key]= document.getElementById(key).value;
	ProjSec = ProjSec + key + "=" + All[key] + "\n";
    }
    
    // Prepare Files section
    let FilesSec = "[Files]\n";
    FilesSec = FilesSec + "fileNamePrefix="+All["fileNamePrefix"]+"\nworkPath="+All["workPath"]+"\n";

    // Prepare ScanSequence section
    let ScanSec = "[ScanSequence]\n";
    strtmp = "scanSeq";
    valtmp = 1*(document.getElementById(strtmp).checked);
    All[strtmp]=valtmp;
    ScanSec = ScanSec + strtmp +"="+ valtmp+"\n";
    let parScan = ["comboScan","scanType","scanFrom","scanStep","scanTo","scanList","scanListdz"];
    for (key of parScan) {
	All[key]= document.getElementById(key).value;
	ScanSec = ScanSec + key + "=" + All[key] + "\n";
    }

    // Collect other parameters
    let parOther = ["parEF", "parESB", "parSHEATH", "parERC", "parRD", "parCA", "parKK0", "parKK0R", "parKDEE1", "parKDEE2", "parIPOT", "parIPOTR", "parIRL"];
    for (key of parOther) {
	All[key]= document.getElementById(key).value;
    }

    // Check ICRU flag, if checked use it
    All["flagICRU"] = document.getElementById("flagICRU").checked;
    
    // Construct full content of cfg file
    TrimSPcfg = FilesSec + LayersSec + ProjSec + ScanSec;
    if (toggle) {
	return All;
    } else {
	return TrimSPcfg;
    }
}

function setValues(content) {
    // This function takes cfg file content and substitutes values in the GUI
    // Split file content into lines
    var event = new Event('change');
    var lines = content.toString().split('\n');
    // Remove comment lines, empty lines and those starting with "["
    var PATTERN= /^(?!\[)(?!\#)(\S)/,
	flines = lines.filter(function (str) {return PATTERN.test(str);});
    for (var i=0; i<flines.length; i++) {
	// Loop over parameters, set appropriate values and trigger associated onChange
	var param=flines[i].replace(/\s+/,'').split('=');
	if (param[0] == 'scanSeq') {
	    // This is a checkbox
	    var seqChecked = true;
	    if (param[1] == 0) {seqChecked = false;}
	    document.getElementById(param[0]).checked = seqChecked;
	    document.getElementById(param[0]).dispatchEvent(event);
	} else {
	    document.getElementById(param[0]).value = param[1];
	    document.getElementById(param[0]).dispatchEvent(event);
	}
    }
}


function CreateInpFile(All) {
    // Create and return input file for the Trim.SP simulation binary
    // Takes object All as input for all relevant parameters 

    // This is the form of the begining of the input file:
    var TemplateFile= " ProjZ ProjAM valEnergy sigEnergy valAngle sigAngle parEF parESB parSHEATH parERC\n numberProj ranSeed ranSeed ranSeed z0 parRD dz parCA parKK0 parKK0R parKDEE1 parKDEE2 parIPOT parIPOTR parIRL";

    // Then comes the number of layers (new format) for example 4 layers:
    // N_Layers=4
    TemplateFile=TemplateFile+"\n"+"N_Layers=numLayer";

    // Then loop over the layers and for each give the following structure
    // thickness, density, correction factor, chemical formula 
    var TemplateLayer = "L1Comp L1d L1rho L1CK\n";
    // Z number of elements
    TemplateLayer += "L1ELZ1 L1ELZ2 L1ELZ3 L1ELZ4 L1ELZ5\n";
    // A number of elements
    TemplateLayer += "L1ELW1 L1ELW2 L1ELW3 L1ELW4 L1ELW5\n";
    // Weigth of element in composition
    TemplateLayer += "L1ELC1 L1ELC2 L1ELC3 L1ELC4 L1ELC5\n";
    TemplateLayer += "L1ELE1 L1ELE2 L1ELE3 L1ELE4 L1ELE5\n";
    TemplateLayer += "L10301 L10302 L10303 L10304 L10305\n";
    TemplateLayer += "0.0000   0.0000   0.0000   0.0000   0.0000\n";
    TemplateLayer += "L1ELST11 L1ELST21 L1ELST31 L1ELST41 L1ELST51\n";
    TemplateLayer += "L1ELST12 L1ELST22 L1ELST32 L1ELST42 L1ELST52\n";
    TemplateLayer += "L1ELST13 L1ELST23 L1ELST33 L1ELST43 L1ELST53\n";
    TemplateLayer += "L1ELST14 L1ELST24 L1ELST34 L1ELST44 L1ELST54\n";
    TemplateLayer += "L1ELST15 L1ELST25 L1ELST35 L1ELST45 L1ELST55";

    let projectile = All['ProjType'];
    All['ProjZ'] = elemPars[projectile].Z;
    All['ProjAM'] = elemPars[projectile].A;

    // This is the flag for checking layers    
    let Check=0;
    let Layer='';
    let Li='';

    // This contains mapped object pairs of original:replace
    let repAll = new Object();
    // Loop over layers an create appropriate values
    for (var i=1; i<=All['numLayer'];i++){
	Li = 'L'+i;
	Layer = TemplateLayer;
	Layer = Layer.replace(/L1/g,Li);
	TemplateFile = TemplateFile+"\n"+Layer;
	Check=0;
	// Composition of layers	
	let LComp="L"+i+"Comp";
	let Comp = document.getElementById(LComp).value;
	All[LComp] = Comp;
	let LElComp=parse_formula(Comp);
	for (key of Object.keys(LElComp)) {
	    // Check if composition is understood
	    if (key=="" || elemPars[key].Z =="") {
		Check++;
	    }  
	}
	if (Comp == "" || typeof Comp == 'undefined') {Check++;}
	// Write composition to results file header

	// Densities of layers
	let Lrho="layer"+i+"rho";
	let rho = 1*All[Lrho];
	
	if (rho=="") {Check++;}
	
	// Thickness of layers
	let Ld ="L"+i+"d";
	let d = All[Ld];
	if (d=="") {Check++;}
	
	// Sanity check, is the layer supposed to have value? are they all there?
	if (Check!=0) {
	    ErrMsg="Error: Bad chemical formula in Layer $i.\nPlease check!\n";
	    console.log($ErrMsg);
	    return ErrMsg;
	}
	
	let tmp = "L"+i+"CK";
	All[tmp]=1.0; 
	
	let Sum = 0;
	for (key of Object.keys(LElComp)) {
	    Sum=Sum+LElComp[key];
	}
	if (Sum==0) {Sum=1;}
	
	let Els = Object.keys(LElComp);
	
	for (let NEl=1;NEl<=5;NEl++) {
	    let El = "";
	    if (NEl <= Els.length) {
		El = Els[NEl-1];
	    }
	    let LEkey = "L"+i+"EL";
	    let ElZ = elemPars[El].Z;
	    let ElW = elemPars[El].A;
	    let ElC = 0;
	    if (LElComp[El] != null){ElC=LElComp[El]/Sum;}
	    let ElE = elemPars[El].Elast;
	    let El030 = 30;
	    if (El=="") { El030 = 0.0;}

	    All[LEkey+"Z"+NEl]=ElZ; 
	    All[LEkey+"W"+NEl]=ElW; 
	    All[LEkey+"C"+NEl]=ElC; 
	    All[LEkey+"E"+NEl]=ElE; 
	    All["L"+i+"030"+NEl]=El030; 
	    
	    let ElSTs = StoppingCoefficients(El,All["flagICRU"]);
	   
	    let j=1;
	    for (let iElST of ElSTs) {
		LEkey = "L"+i+"ELST"+NEl+j;
		j++;
		All[LEkey]=iElST; 
	    }
	}
    }

    for (let key of Object.keys(All)) {
	if (All[key]!=null){
	    if (key=="ranSeed") {
		// Seed repeats three times
		TemplateFile = TemplateFile.replace(/ranSeed/g,All[key]);
	    } else {
		TemplateFile = TemplateFile.replace(key,All[key]);
	    }
	}
    }
    return TemplateFile;
}

function replaceAll(str,mapObj){
    // Takes string str and replaces all mapped objects in it
    // The mapped object are pairs of original:replace
    var re = new RegExp(Object.keys(mapObj).join("|"),"gi");

    return str.replace(re, function(matched){
        return mapObj[matched.toLowerCase()];
    });
}

function sum(array){
    // Takes and array and returns the sum of its elements
    let sum_array = array.reduce(function(a, b){
        return a + b;
    }, 0);
    return sum_array;
}

function startSequence(All) {
    let cmd = '';
    let trimBin = All['trimPath']+"/trimspNL";
    let randStr = '';
    let webOrApp = amIWeb();
    // Only for Node.js 
    if (!webOrApp) {
	// Check if the trimspNL binary is found
	if (!fileExists(trimBin)) {
	    // check if it is in rpm
	    trimBin = "/usr/lib/TrimSP/resources/app/trimspNL";
	    if (!fileExists(trimBin)) {
		// if not found, try in PATH and hope for the best
		trimBin = "trimspNL";
	    }
	}
	// Check if workPath exists otherwise create it
	checkDir(All['workPath']); // from TrimSPelec.js, Electron/Node specific
    } else {
	// Add random string (5 char) to file names
	randStr = (Math.random() + 1).toString(36).substring(7);
	All["fileNamePrefix"] = randStr;
	All["workPath"] = "/tmp/" + randStr;
    }
    
    let Progress =0;
    document.getElementById("pBar").style.width = Progress + "%";
    document.getElementById("pBar").innerHTML = Progress + "%";

    // This is a flag to indicate whether the lists of values and inclements are the same size
    All["SdzFlag"]=0;
    var SValues = [];
    let ScanName = "E";
    let ScanAttrib = "valEnergy";
    // Generate an arry of scanned values (one element for a single run)
    if (All["scanSeq"]) {
	// For multiple runs or a scan
	if (All["scanType"]=="scanVals") {
	    var SValues=All["scanList"].split(/,/);
	    var SdzValues=All["scanListdz"].split(/,/);
	    if (SValues.length == SdzValues.length) {All["SdzFlag"]=1;}
	} else {
	    for (let Val=parseInt(All["scanFrom"]);Val<=parseInt(All["scanTo"]);Val=Val+parseInt(All["scanStep"])) {
		SValues.push(Val);
	    }
	}

	if (All["comboScan"]==1) {
	    ScanName = "SigE";
	    ScanAttrib = "sigEnergy";
	} else if (All["comboScan"]==2) {
	    ScanName = "Angle";
	    ScanAttrib = "valAngle";
	} else if (All["comboScan"]==3) {
	    ScanName = "SigAngle";
	    ScanAttrib = "sigAngle";
	} else if (All["comboScan"]==4) {
	    ScanName = "N";
	    ScanAttrib = "numberProj";
	} else if (All["comboScan"]==5) { 
	    ScanName = "Ld"+All["scandL"];
	    ScanAttrib = "L"+All["scandL"]+"d";
	}
    } else {
	// For single run, array with single value of valEnergy
	SValues.push(parseInt(All["valEnergy"]));
    }

    // Now start the actual simulation
    //setInterval(() => {
    let iScan=0;
    for (var SValue of SValues) {
	// Update value in GUI
	document.getElementById(ScanAttrib).value = SValue;
	All[ScanAttrib]=SValue;
	if ( All["SdzFlag"] == 1) {
	    if (All["comboScan"]=="Energy") {
		document.getElementById(ScanAttrib).value = SdzValues[iScan];
	    } else if (All["comboScan"]=="") {
		document.getElementById(ScanAttrib).value = SdzValues[iScan];
	    }
	}
	// Update GUI progress bar
	Progress=Math.round(Progress+90/SValues.length);
	document.getElementById("pBar").style.width = Progress + "%";
	document.getElementById("pBar").innerHTML = Progress + "%";
	
	// Single run: Start 
	let eingabe1=CreateInpFile(All);
	if (eingabe1=="ERROR") {return(0);}
	let FILENAME=All["workPath"]+"/"+All["fileNamePrefix"]+"_"+ScanName+SValue;
	writeAsciiFile(FILENAME+".inp",eingabe1);
	if (!webOrApp) {
	    // Prepare command and execute
	    cmd = "cd " + All["workPath"];
	    cmd += ";cp " + FILENAME + ".inp eingabe1.inp";
	    cmd += ";" + trimBin;
	    cmd += "; mv -f ausgabe1.rge " + FILENAME + ".rge";
	    cmd += "; mv -f ausgabe1.out " + FILENAME + ".out";
	    cmd += "; mv -f ausgabe1.err " + FILENAME + ".err";
	    execute(cmd);
	}
	// Single run: End

	// Read stopping profiels
	let [cols,data]= readDatFile(FILENAME+".rge");
	// convert depth to nm and normalize stopping profile
	let depth=data[0];
	let nmuons=data[1];
	let dz = (depth[1]-depth[0])/10;
	let norm = dz*sum(nmuons)/100;
	for (let i=0; i<depth.length; i++) {
	    depth[i]=depth[i]/10;
	    nmuons[i]=nmuons[i]/norm;
	}
	Plot_xy("plotRge",depth,nmuons,['Depth (nm)','Stopped muons (%/nm)',ScanName+'='+Number(SValue)/1000+'keV']);		
	// Read the sequence data
	let [cfort,cdata]= readDatFile(All["workPath"]+"/fort.33");
	let lyrs = [6]; // back scattered muons
	for (let ilayer=18;ilayer<cdata.length;ilayer++){lyrs.push(ilayer);} // the rest of the layers
	// Now loop over all
	Plotly.purge("plotFrac")
	for (let ilayer of lyrs) {
	    // Normalize
	    let idata = cdata[ilayer];
	    for (let i=0; i<idata.length; i++) {
		idata[i]=100*idata[i]/cdata[4][i];
	    }
	    let chem = cfort[ilayer];
	    if (ilayer != 6) {
		let LComp = "L"+(ilayer-17)+"Comp";
		chem = All[LComp];
	    }
	    Plot_xy("plotFrac",cdata[0],cdata[ilayer],['E (keV)','Fraction of muons (%)',chem]);
	}
	iScan++;
    }

    let seq_file = All["fileNamePrefix"]+"_Seq_Results.dat";

    // Remove redundant files and change the name fort.33
    if (!webOrApp) {
	cmd="cd " + All["workPath"] + ";rm -f eingabe1.inp; mv -f fort.33 " + seq_file;
	execute(cmd);
    }
    Progress=100;
    document.getElementById("pBar").style.width = Progress + "%";
    document.getElementById("pBar").innerHTML = Progress + "%";
    return(0);
}

function readDatFile(filename) {
    // Read column data file and return
    // cols - labels of columns
    // data - 2D array with the columns
    let lines = "";
    lines = readAsciiFile(filename);
    
    let data = [];
    let i=0; // line counter
    for (let line of lines.trim().split('\n')) {
	// take labels from the first row
	if (i==0) {
	    var cols = line.trim().split(/[#\s]+/g);
	} else {
	    let words = line.trim().split(/[#\s]+/g);
	    for (let j=0; j<cols.length;j++) {
		if (data[j] == null) {data[j]=[];}
		data[j].push(parseFloat(words[j]));
	    }
	}
	i++;
    }
    return [cols,data];
}

function plotProfiles(filenames) {
    // Plot rge files filenames

    var win = window.open("", "_blank", "toolbar=no, menubar=no");
    win.document.open();
    win.document.write('<html><head><link rel="stylesheet" href="plotly.css"></head><body>');
    win.document.write('<table style="width: 100%"><tr><td><div id="newPlot"><!-- Plotly chart will be drawn inside this DIV --></div></td></tr></table>');
    win.document.write('</body></html>');
    win.addEventListener('resize', sizePlot);
    win.document.close();
    var plotDiv=win.document.getElementById("newPlot");

    // Extract energies from run files if available
    var files= new Object();
    var Es = [];
    for (let i=0;i<filenames.length;i++) {
	Es[i]=Number(filenames[i].substring(filenames[i].indexOf('_')+2,filenames[i].indexOf('.')));
	files[Es[i]] = filenames[i];
    }

    // loop on sorted values and plot
    for (let i=0;i<Es.length;i++) {
	let [cols,data]= readDatFile(files[Es[i]]);
	// convert depth to nm and normalize profile
	let depth=data[0];
	let nmuons=data[1];
	let dz = (depth[1]-depth[0])/10;
	let norm = dz*sum(nmuons)/100;
	for (let i=0; i<depth.length; i++) {
	    depth[i]=depth[i]/10;
	    nmuons[i]=nmuons[i]/norm;
	}
	Plot_xy(plotDiv,depth,nmuons,['Depth (nm)','Stopped muons (%/nm)','E='+(Es[i]/1000)+'keV']);		
    }
    
}

function plotFractions(filename) {
    // Plot fractions stopped in layers from sequence file

    var win = window.open("", "_blank", "toolbar=no, menubar=no");
    win.document.open();
    win.document.write('<html><head><link rel="stylesheet" href="plotly.css"></head><body>');
    win.document.write('<table style="width: 100%"><tr><td><div id="newPlot"><!-- Plotly chart will be drawn inside this DIV --></div></td></tr></table>');
    win.document.write('</body></html>');
    win.addEventListener('resize', sizePlot);
    win.document.close();
    var plotDiv=win.document.getElementById("newPlot");

    var [cfort,cdata]= readDatFile(filename);
    let lyrs = [6]; // back scattered muons
    for (let ilayer=18;ilayer<cdata.length;ilayer++){lyrs.push(ilayer);} // the rest of the layers
    // Now loop over all
    for (let ilayer of lyrs) {
	// Normalize
	let idata = cdata[ilayer];
	for (let i=0; i<idata.length; i++) {
	    idata[i]=100*idata[i]/cdata[4][i];
	}
	Plot_xy(plotDiv,cdata[0],cdata[ilayer],['E (keV)','Fraction of muons (%)',cfort[ilayer]]);
    }
    plotDiv=win.document.getElementById("newPlot");
}

function plotMean(filename) {
    // Plot mean and straggeling from sequence file

    var win = window.open("", "_blank", "toolbar=no, menubar=no");
    win.document.open();
    win.document.write('<html><head><link rel="stylesheet" href="plotly.css"></head><body>');
    win.document.write('<table style="width: 100%"><tr><td><div id="newPlot" style="width: 500px; height: 400px;"><!-- Plotly chart will be drawn inside this DIV --></div></td></tr></table>');
    win.document.write('</body></html>');
    win.addEventListener('resize', sizePlot);
    win.document.close();
    var plotDiv=win.document.getElementById("newPlot");
    
    let [cfort,cdata]= readDatFile(filename);
    let mean = cdata[10];
    let strag = cdata[11];
    for (let i=0; i<mean.length; i++) {
	mean[i]=mean[i]/10;
	strag[i]=strag[i]/10;
    }
    Plot_xy(plotDiv,cdata[0],mean,['E (keV)','Mean Depth/Stragg. (nm)',cfort[10]]);
    Plot_xy(plotDiv,cdata[0],strag,['E (keV)','Mean Depth/Stragg. (nm)',cfort[11]]);
}

function startSim() {
    // Collect data from GUI
    var All=prep_cfg(1);
    // Switch to plots tab
    document.getElementById("btnPlots").click();
    // Clear plots first
    Plotly.purge("plotFrac")
    Plotly.purge("plotRge")

    // start simulation sequence
    startSequence(All)
    //CreateInpFile(All);
    //  document.location =
    //
    //  "http://musruser.psi.ch/cgi-bin/TrimSP.cgi?TrimSPcfg="+TrimSPcfg+'go=start';
}

function amIWeb() {
    if (typeof module !== 'undefined' && module.exports) {
	// Run as standalone app
	return 0;
    } else {
	// Run as a web app
	return 1;
    }
}

