CREATE PROCEDURE dbo.GetExtrasCalculated @AReferenceNumber INT, @AGuestNumber INT, @AAddressTypeNumber INT, @ATotalPrice FLOAT OUTPUT AS
BEGIN
  SET NOCOUNT ON
  DECLARE @DiscountType INT
  DECLARE @ReferenceNumber INT
  DECLARE @GuestNumber INT
  DECLARE @WareNumber INT
  DECLARE @WarePrice FLOAT
  DECLARE @WarePieces INT
  DECLARE @DiscountRate FLOAT 
  DECLARE @DiscountIsFixedAmount BIT 
  DECLARE @TotalPrice FLOAT
  DECLARE @DiscountAmount FLOAT
  DECLARE @DiscountAllowed BIT

  SET @ReferenceNumber = @AReferenceNumber
  SET @GuestNumber = @AGuestNumber
  SET @WareNumber = -1

  SELECT @DiscountType = DiscountCustomerType FROM Reservations WITH (NOLOCK) WHERE ReferenceNumber = @ReferenceNumber AND GuestNumber = @GuestNumber

  SELECT @TotalPrice = SUM(TotalPrice)
  FROM ArrangementLines WITH (NOLOCK)
  INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber AND ArrangementReservationsXtab.ReferenceNumber = @ReferenceNumber AND ArrangementReservationsXtab.GuestNumber = @GuestNumber
  WHERE (1=1)
    AND (ISNULL(ArrangementLines.PacketItemNumber, 0) = 0)
    AND (ISNULL(ArrangementLines.FK_ExDepartment, 0) > 0)
    AND (ISNULL(ArrangementLines.Price, 0) <> 0)

  DECLARE TmpCursor CURSOR FOR
    SELECT ArrangementLines.WareNumber, ArrangementLines.Price,  ArrangementLines.Pieces, Ware.ReservationDiscount
    FROM ArrangementLines WITH (NOLOCK)
    INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber
    INNER JOIN Ware WITH (NOLOCK) ON Ware.WareNumber = ArrangementLines.WareNumber
    WHERE ArrangementReservationsXtab.ReferenceNumber = @ReferenceNumber
    AND ArrangementReservationsXtab.GuestNumber = @GuestNumber
    AND ISNULL(ArrangementLines.PacketItemNumber,0)=0
  OPEN TmpCursor
  FETCH NEXT FROM TmpCursor INTO @WareNumber, @WarePrice, @WarePieces, @DiscountAllowed
  WHILE (@@FETCH_STATUS<>-1)
  BEGIN
    SET @DiscountAmount = 0

    IF @DiscountAllowed = 1
    BEGIN
      EXEC GetDiscountRateWare @ReferenceNumber, @GuestNumber, @WareNumber, @DiscountType, @DiscountRate OUTPUT, @DiscountIsFixedAmount OUTPUT
      IF @DiscountIsFixedAmount = 1
	      SET @DiscountAmount = (@WarePieces * @DiscountRate)
      ELSE IF @DiscountRate > 0
	      SET @DiscountAmount = (((@WarePieces * @WarePrice) * @DiscountRate) / 100.0)
    END

    SET @TotalPrice = (@TotalPrice - @DiscountAmount)
    FETCH NEXT FROM TmpCursor INTO @WareNumber, @WarePrice, @WarePieces, @DiscountAllowed
  END

  SET @ATotalPrice = @TotalPrice

  CLOSE TmpCursor
  DEALLOCATE TmpCursor
END