diff --git a/xgm.py b/xgm.py
index dbc3eb7732f313fdec3f2ecb3ad38b7dedc0ea0e..f45a4cffbb98c055f03b30d34d2b0efe1d1246e8 100644
--- a/xgm.py
+++ b/xgm.py
@@ -395,6 +395,7 @@ def getTIMapd(data, mcp=1, use_apd=True, intstart=None, intstop=None,
         The missing values, in case of change of number of pulses, are filled
         with NaNs.
         
+        Inputs:
             data: xarray Dataset containing MCP raw traces (e.g. 'MCP1raw')
             intstart: trace index of integration start
             intstop: trace index of integration stop
@@ -721,4 +722,44 @@ def checkTimApdWindow(data, mcp=1, use_apd=True, intstart=None, intstop=None):
         ax2.legend(lines + lines2, labels + labels2, loc=0)
     else:
         ax.legend(loc='lower left')
-    plt.tight_layout()
\ No newline at end of file
+    plt.tight_layout()
+    
+def matchXgmTimPulseId(data, use_apd=True, intstart=None, intstop=None,
+                       bkgstart=None, bkgstop=None, t_offset=None, 
+                       npulses=None):
+    ''' Function to match XGM pulse Id with TIM pulse Id.
+        Inputs:
+            data: xarray Dataset containing XGM and TIM data
+            use_apd: bool. If True, uses the digitizer APD ('MCP[1,2,3,4]apd').
+                     If False, peak integration is performed from raw traces.
+                     All following parameters are needed in this case.
+            intstart: trace index of integration start
+            intstop: trace index of integration stop
+            bkgstart: trace index of background start
+            bkgstop: trace index of background stop
+            t_offset: index separation between two pulses
+            npulses: number of pulses to compute
+            
+        Output:
+            xr DataSet containing XGM and TIM signals with the share 
+            dimension 'pId'. Raw traces, raw XGM and raw APD are dropped.
+    '''
+    res = selectSASEinXGM(data, xgm='SCS_XGM').rename({'XGMbunchId':'pId'})
+    res2 = selectSASEinXGM(data, xgm='SA3_XGM').rename({'XGMbunchId':'pId'})
+    dropList = ['SCS_XGM','SA3_XGM']
+    mergeList = [res, res2]
+    for mcp in range(1,5):
+        if 'MCP{}apd'.format(mcp) in data or 'MCP{}raw'.format(mcp) in data:
+            MCPapd = getTIMapd(data, mcp=mcp, use_apd=use_apd, intstart=intstart, intstop=intstop,
+                              bkgstart=bkgstart, bkgstop=bkgstop, t_offset=t_offset, 
+                              npulses=npulses).rename('MCP{}apd'.format(mcp))
+            if use_apd:
+                MCPapd = MCPapd.rename({'apdId':'pId'})
+            else:
+                MCPapd = MCPapd.rename({'MCP{}fromRaw'.format(mcp):'pId'})
+                dropList.append('MCP{}raw'.format(mcp))
+            mergeList.append(MCPapd)
+            dropList.append('MCP{}apd'.format(mcp))
+    mergeList.append(data.drop(dropList))
+    subset = xr.merge(mergeList, join='inner')
+    return subset