CREATE FUNCTION [dbo].[GetTransactionCount] (@AFolio int, @AReference int, @AGuest int, @APrinted bit, @ABehind bit)  
RETURNS int AS  
BEGIN 
  DECLARE @LCount int
  
  IF @AReference > 0
    SELECT @LCount = COUNT(*) FROM Transactions TR (NOLOCK)
      INNER JOIN Folios F (NOLOCK) ON F.FolioNumber = TR.FolioNumber
      LEFT JOIN dbo.InvoiceTransactionXtab ITX WITH (NOLOCK) ON ITX.FkTransaction = TR.TransactionNumber
      LEFT JOIN dbo.Invoice I WITH (NOLOCK) ON ITX.FkInvoice = I.PkInvoice
    WHERE F.ReferenceNumber = @AReference AND (@AGuest = -1 OR F.GuestNumber = @AGuest)

      AND ISNULL(TR.PriceOverwrite, 0) <> 0
      AND ISNULL(TR.Moveddeleted, 0) = 0 AND (@ABehind = 1 OR (@ABehind = 0 AND ISNULL(TR.ShowOnBillFlag, 0) = 1))
      AND (@APrinted IS NULL OR @APrinted  = 1 AND NOT ITX.FkInvoice IS NULL AND I.CancelDate IS NULL OR @APrinted  = 0 AND (
		SELECT TOP 1 ITX1.FkInvoice FROM InvoiceTransactionXTab ITX1 WITH (NOLOCK)
          INNER JOIN Invoice I1 WITH (NOLOCK) ON ITX1.FkInvoice = I1.PkInvoice
        WHERE ITX1.FkTransaction = TR.TransactionNumber AND I1.CancelDate IS NULL
        ORDER BY I1.PkInvoice DESC) IS NULL )
  ELSE
    SELECT @LCount = COUNT(*) FROM Transactions TR (NOLOCK)
      LEFT JOIN dbo.InvoiceTransactionXtab ITX WITH (NOLOCK) ON ITX.FkTransaction = TR.TransactionNumber
      LEFT JOIN dbo.Invoice I WITH (NOLOCK) ON ITX.FkInvoice = I.PkInvoice
    WHERE TR.FolioNumber =  @AFolio

      AND ISNULL(TR.PriceOverwrite, 0) <> 0
      AND ISNULL(TR.Moveddeleted, 0) = 0 AND (@ABehind = 1 OR (@ABehind = 0 AND ISNULL(TR.ShowOnBillFlag, 0) = 1))
      AND (@APrinted IS NULL OR @APrinted  = 1 AND NOT ITX.FkInvoice IS NULL AND I.CancelDate IS NULL OR @APrinted  = 0 AND (
		SELECT TOP 1 ITX1.FkInvoice FROM InvoiceTransactionXTab ITX1 WITH (NOLOCK)
          INNER JOIN Invoice I1 WITH (NOLOCK) ON ITX1.FkInvoice = I1.PkInvoice
        WHERE ITX1.FkTransaction = TR.TransactionNumber AND I1.CancelDate IS NULL
        ORDER BY I1.PkInvoice DESC) IS NULL )
  
  IF @LCount IS NULL
    SET @LCount = 0

  RETURN @LCount
END