Average Delay Payment calculation

I need to calculate the average delay of customer payments. I wrote a function that - for every customer - filter CustLedgerEntry for closed Invoices and calculate the difference between the date the Invoice was closed (I don’t consider partialpayment) and the original Due date. I’ve got a doubt: if the invoice was closed by means of a Credit Memo should I consider the posting date of the Credit memo? Besides in that DB users usually apply the Invoice to the payment (I mean, doing a manual application they set The Invoice as the applying entry , as a result is the payment Customer ledger Entry with values in Closed at date and Closed By Entry No. fields).

Does anybody has never done something similar?

Any advise?