CREATE PROCEDURE [dbo].[RecalcForecastDaily] @CalcForecastFromDate Char(8) = '' , @DebugReferenceNumber INT = -1  AS
SET NOCOUNT ON

/*
  Changes:
    KJ 20120628: Bug: Fix for "Booked columns empty after nightaudit". Case #CR044732
    KJ 20120615: Bug: Fix for "Discount Calculated on wrong day for departure day".
    KJ 20120613: Bug: Fix for "+product res with departure on recalc data now calculated".
    KJ 20120607: Bug: Fix for "Wrong date on package when +product". Case #CR043844
    KJ 20120606: Bug: Fix for "Wrong pacage when +product". Case #CR043844
    KJ 20120606: Bug: Fix for "Discount in package not calculated correct". Case #CR043844
    KJ 20120510: Bug: Fix for "Wrong calc of discount when different splitbill on +product". Case #CR043189
    KJ 20120103: Bug: Fix for "Department sometimes NULL when calculating Discount". Case #CR038190
    KJ 20111207: Bug: Fix for "Department sometimes NULL when calculating Discount". Case# CR037459
    KJ 20110919: Bug: Fix for "Debtype 2+6+9 wrong calculated when priceoverwritten or when running PackagesplitAfterReduction". Case #CR034026
    KJ 20110727: Ext: Menuware and discount. Req# 952
    KJ 20110615: Bug: Fix for "Discount not calculated". Case# CR024218
    KJ 20100714: Bug: Fix for "PriceOverwritten sometimes NULL"
    KJ 20100602: Bug: Fix for "Customer/hotel sometimes marked as deleted"
    KJ 20100518: Bug: Fix for "halls without products shall not be calculated with package"
    KJ 20100426: Bug: Fix for "Cannot Insert the value NULL into column 'firstPrice'"
    KJ 20100416: Bug: Fix for "Aritmetic overflow for data type tinyint"
    KJ 20100215: Bug: Extras without department not included when running all extras 
    KJ 20100212: Bug: Fix for "Wronig department for rooms and no product."
    KJ 20100209: Bug: Fix for "Wrong department is no room is allocated"
    KJ 20100128: Ext: Makeing it more secure to only include extras and not package linies with faulty department
    KJ 20100111: Ext: Added @Budget Extra - setup to select if all extras og only extracharge extras should be added
    KJ 20090910: Ext: Enable budget per department and charge department enabled
    KJ 20090825: Ext: Use chargedepartment from ReservationConferenceLine
    KJ 20090812: Ext: Enable budget per department
    KJ 20081118: Bug: Fix for "Major rewrite for dayproducts"
    KJ 20081114: Bug: Fix for "Addon on +Product not correct calculated when NOT priceoverwrite"
    KJ 20081112: Bug: Fix for "Use the AddonIfPriceOverwritten setting if addon and priceoverwrite"
    KJ 20081112: Bug: Fix for "Only null+empty package on overnight products"
    KJ 20081104: Bug: Fix for "Also include tables in calculation"
    KJ 20080311: Bug: Fix for "Wrong calc when priceoverwrite an price is 0 on halls"
    KJ 20080229: Bug: Another try to fix "Not correct calc when priceoverwrite"
    KJ 20071121: Bug: Another try to fix "+product calculated wrong"
    KJ 20071114: Bug: Fix for "+product calculated wrong"
    KJ 20071114: Bug: Fix for "Do not use totalprice for extras"
    KJ 20071114: Bug: Fix for "Arrangmentlines - Extras Not all lines included if same price - Distinct eliminates Arrangementlinenumber added to select"
    KJ 20070926: Bug: Fix for Adults, Children1 and Children 2 is sometimes NULL
    KJ 20070926: Bug: Added ISNULL for @DebugReferenceNumber
    KJ 20070703: Some Bugfixes.
    KJ 20070703: Added @DebugReferenceNumber for debug purpose.  
    KJ 20070703: Look at Bookedtypenumber also for Guest = 0
    KJ 20070524: Bug: Fix for Halls without type calculated wrong
    KJ 20070521: Bug: Fix for Postering by VAT wrong. Wrong accountnumber.
    KJ 20070320: Fix for PaysAduls not correct when namelist is created.
    KJ 20070314: Removed constraints from #DayProducts internal table - not used.
    KJ 20070305: Use FK_ExDepartment
    KJ 20070305: BUG Fix for "DayProducts and not fixedPrice calculated wrong"
    KJ 20070305: Added some debug stuff
    KJ 20070303: Fix for Sometimes package departments are added as manuel line
    KJ 20070226: Some bugfixes.
    KJ: 20070223: Fix for "Not correct calc when priceoverwrite"
    KJ: 20070223: VAT for overnight never calculated
    KJ: 20070223: Extras should be posted without VAT
    KJ: 20070220: Added LastForecastUpdate
    KJ: 20070215: A shit load of bugfixes
    KJ: 20070213: Do not include waitinglist
    KJ: 20070213: Added @ShowPrint
    KJ: 20070212: Do not delete data for dates before reservation clenup date
    KJ: 20070104: Added support for Halls on subres
    KJ: 20061228: Fix for Can not insert NULL into field PriceProduct
*/

DECLARE @ShowPrint BIT
SET @ShowPrint = 0
DECLARE @ShowDebug BIT
SET @ShowDebug = 0
DECLARE @DebugStartDate CHAR(8)
DECLARE @DebugEndDate CHAR(8)
SET @DebugStartDate = '20070101'
SET @DebugEndDate = '20071231'

DECLARE @TmpCalcForecastFromDate DATETIME
SET @TmpCalcForecastFromDate = CONVERT(DATETIME, @CalcForecastFromDate, 112)-1
SET @CalcForecastFromDate = CONVERT(CHAR(8), @TmpCalcForecastFromDate, 112)

Declare @CentralBookingType smallint
Select @CentralBookingType = Convert(Integer,isnull(KeyValue,0)) from HotelSetup WITH (Nolock) where searchkey like '%CentralBookingType%'

Declare @FormatedStartDate Char (8)
SET @FormatedStartDate = @CalcForecastFromDate

Declare @IncludeTentative bit
Select @IncludeTentative = Convert(Bit, KeyValue) from Hotelsetup WITH (nolock) where Searchkey = 'IncludeTentativeInMISAndOrderbook'
if isnull(@IncludeTentative,0)=0 SET @IncludeTentative=0

Declare @IncludeDayroomsInSoldRooms Bit
SELECT @IncludeDayroomsInSoldRooms=Convert(Bit,KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE Upper (SearchKey)=Upper('IncludeDayroomsInSoldRooms')

Declare @NightAuditRunning Bit
Select @NightAuditRunning = NightAuditRunning from Terminals WITH (nolock) where NightAuditRunning = 1
if isnull(@NightAuditRunning,0)=0 SET @NightAuditRunning = 0

Declare @GetVATFrom Smallint
SELECT @GetVATFrom = Convert(smallint,KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE Upper(SearchKey) = Upper('BookkeepingReport')

Declare @Arr24 char(5)
Select @Arr24 = KeyValue from HotelSetUp WITH (NOLOCK)  Where  SearchKey='Arr24HoursStarts'

Declare @NameListSetting Tinyint
Declare @NameListSettingHotelSetup Tinyint
Select @NameListSettingHotelSetup = Convert(Integer, KeyValue) from Hotelsetup WITH (nolock) where Searchkey = 'NameListReservationPerPerson'

Declare @OnePersonPaysForAll bit
Select @OnePersonPaysForAll = CONVERT(Bit,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='OnePersonPaysForAll'
if isnull(@OnePersonPaysForAll,0)=0 SET @OnePersonPaysForAll=0

Declare @SystemDateStr Char (8)
Declare @SystemDate DateTime
SELECT  @SystemDateStr = SYSTEMDATE FROM System WITH (nolock)  WHERE NUMBER = 1  -- Only one record
SET @SystemDate = Convert(DateTime,@SystemDateStr)

Declare @DayroomsLaterThanTime char(5)
SELECT @DayroomsLaterThanTime=KeyValue FROM HotelSetup WITH (NOLOCK) WHERE Upper (SearchKey)=Upper('DayroomsLaterThanTime')

Declare @TotalOtherExtraOnDay Money
Declare @TotalRestExtraOnDay Money

Declare @VatValueWareText varchar(5)

Declare @VatValueIndex0 Float
Declare @VatValueIndex1 Float
Declare @VatValueIndex2 Float
Declare @VatValueIndex3 Float
Declare @VatValueIndex4 Float
Declare @VatValueIndex5 Float

DECLARE @VatValueWare FLOAT
DECLARE @VatValueNumber INT

Declare @VATOfTotalRestExtraOnDay Money
Declare @VATOfTotalOtherExtraOnDay Money

Declare @LogiWareIndex int

SET @VatValueIndex0 = 0

Select @VatValueWareText = KeyValue from HotelSetUp WITH (NOLOCK)  Where  SearchKey='VATValue1'
if (charindex(',',@VatValueWareText)>0)
  SET @VatValueWareText = STUFF(@VatValueWareText, charindex(',',@VatValueWareText) ,1, '.')
SET @VatValueIndex1 = CONVERT(Float,@VatValueWareText) 

Select @VatValueWareText = KeyValue from HotelSetUp WITH (NOLOCK)  Where  SearchKey='VATValue2'
if (charindex(',',@VatValueWareText)>0)
  SET @VatValueWareText = STUFF(@VatValueWareText, charindex(',',@VatValueWareText) ,1, '.')
SET @VatValueIndex2 = CONVERT(Float,@VatValueWareText) 

Select @VatValueWareText = KeyValue from HotelSetUp WITH (NOLOCK)  Where  SearchKey='VATValue3'
if (charindex(',',@VatValueWareText)>0)
  SET @VatValueWareText = STUFF(@VatValueWareText, charindex(',',@VatValueWareText) ,1, '.')
SET @VatValueIndex3 = CONVERT(Float,@VatValueWareText) 

Select @VatValueWareText = KeyValue from HotelSetUp WITH (NOLOCK)  Where  SearchKey='VATValue4'
if (charindex(',',@VatValueWareText)>0)
  SET @VatValueWareText = STUFF(@VatValueWareText, charindex(',',@VatValueWareText) ,1, '.')
SET @VatValueIndex4 = CONVERT(Float,@VatValueWareText) 

Select @VatValueWareText = KeyValue from HotelSetUp WITH (NOLOCK)  Where  SearchKey='VATValue5'
if (charindex(',',@VatValueWareText)>0)
  SET @VatValueWareText = STUFF(@VatValueWareText, charindex(',',@VatValueWareText) ,1, '.')
SET @VatValueIndex5 = CONVERT(Float,@VatValueWareText) 

if isnull(@VatValueIndex1,0) = 0  SET @VatValueIndex1 = 0
if isnull(@VatValueIndex2,0) = 0  SET @VatValueIndex2 = 0
if isnull(@VatValueIndex3,0) = 0  SET @VatValueIndex3 = 0
if isnull(@VatValueIndex4,0) = 0  SET @VatValueIndex4 = 0
if isnull(@VatValueIndex5,0) = 0  SET @VatValueIndex5 = 0

/***** CONf LINES***********/
Declare @GenerateDayProduct Bit
Declare @PacketNumberReservation int
Declare @ArrArrivalTime char(5)
Declare @ArrDepartureTime char(5)
/***** /CONf LINES***********/

Declare @LINENUMBER Int
Declare @BookedTypeNumber Int
Declare @RoomNumber Int
Declare @ReferenceNumber int
Declare @GuestNumber Integer
Declare @Status SmallInt
Declare @SegmentNumber	integer
Declare @PointOfSaleNumber	integer
Declare @ArrivalDate Char(8)
Declare @DepartureDate Char(8)
Declare @DepartureTime Char(5)
Declare @Adults integer
Declare @Children1 integer
Declare @Children2 integer
Declare @PaysAdults integer
Declare @PaysChildren1 integer
Declare @PaysChildren2 integer

Declare @ProductNumber Int
Declare @ProductNumber2 Int
Declare @ProductNumber3 Int
Declare @ProductNumber4 Int

Declare @NumberOfRooms SmallInt

Declare @PriceOverwritten Bit
Declare @PriceOverwritten2 Bit
Declare @PriceOverwritten3 Bit
Declare @PriceOverwritten4 Bit

Declare @Price Money
Declare @FirstPrice1 Money
Declare @FirstPrice2 Money
Declare @FirstPrice3 Money
Declare @FirstPrice4 Money

Declare @Day SmallInt
Declare @Day2 SmallInt
Declare @Day3 SmallInt
Declare @Day4 SmallInt

Declare @ConferenceLineOnRes Bit
Declare @ConflineOnMainRes bit
Declare @HotelCustomerNumber int

Declare @SmallestArrivalDate Char(8)
Declare @BiggestDepartureDate Char(8)

Declare @BookedNumberOfRooms Integer

Declare @TotalPriceDay Money
Declare @PriceWithoutPackage Money

DECLARE @FK_ExDepartment SMALLINT
DECLARE @FK_LogiDepartment SMALLINT
DECLARE @tmpDepartment SMALLINT
DECLARE @TheDepartmentNumber SMALLINT
DECLARE @FK_ChargeDepartment SMALLINT

DECLARE @OrderBookBudgetCalcDiscount BIT
DECLARE @DiscountWareNumber INT
DECLARE @DiscountResultAccountNumber INT
DECLARE @DiscountAsNettoPrice BIT
DECLARE @ExtraGuestNumber INT
DECLARE @ExtraWareNumber INT
DECLARE @SplitBillNumber INT
DECLARE @SplitBillNumber1 INT
DECLARE @SplitBillNumber2 INT
DECLARE @SplitBillNumber3 INT
DECLARE @SplitBillNumber4 INT
DECLARE @FolioNumber INT
DECLARE @AddressType INT
DECLARE @AllDiscountRate FLOAT
DECLARE @DiscountRate FLOAT
DECLARE @DiscountPrice MONEY
DECLARE @ChargeDiscountAsProduct BIT
DECLARE @DiscountVatValueWare FLOAT
DECLARE @PackagesplitAfterDiscount BIT
DECLARE @IsFixedPriceProduct BIT
DECLARE @CalcDiscount BIT
DECLARE @DiscountValue FLOAT

DECLARE @IsMenuWare BIT
DECLARE @SumPercentage INT
DECLARE @HandleAsMenuWare BIT
DECLARE @MenuVatValueNumber INT
DECLARE @MenuWareResultAccountNumber INT
DECLARE @MenuVatValueWare FLOAT
DECLARE @MenuProcentage INT 
DECLARE @MenuWarePrice FLOAT
DECLARE @WarePriceExVat FLOAT

SELECT @OrderBookBudgetCalcDiscount = CONVERT(BIT, KeyValue) FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'OrderBookBudgetCalcDiscount'
SET @OrderBookBudgetCalcDiscount = ISNULL(@OrderBookBudgetCalcDiscount, 0)

SET @DiscountWareNumber = 0	

SELECT @DiscountWareNumber = WareNumber, @DiscountResultAccountNumber = ResultAccountNumber, @VatValueNumber = Accounts.VatValueNumber
FROM Ware WITH (NOLOCK) 
INNER JOIN  WareGroups WITH (NOLOCK) ON Ware.WareGroupNumber = WareGroups.WareGroupNumber
INNER JOIN Accounts WITH (NOLOCK) ON Accounts.AccountNumber = Ware.ResultAccountNumber
WHERE Ware.SortNumber=10
AND Ware.MarkAsDeleted IS NULL
AND WareGroups.Payment=5 
AND ((WareGroups.MarkAsDeleted is null) OR (WareGroups.MarkAsDeleted='0')) 

SET @DiscountVatValueWare = CASE @VatValueNumber
  WHEN 1 THEN @VatValueIndex1
  WHEN 2 THEN @VatValueIndex2
  WHEN 3 THEN @VatValueIndex3
  WHEN 4 THEN @VatValueIndex4
  WHEN 5 THEN @VatValueIndex5
END
SET @DiscountVatValueWare = ISNULL(@DiscountVatValueWare, 0)

SELECT @DiscountAsNettoPrice = ISNULL(KeyValue,0) FROM HotelSetup WITH (NOLOCK) WHERE Searchkey = 'DiscountAsNettoPrice'

SELECT @ChargeDiscountAsProduct = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'ChargeDiscountAsProduct'
IF ISNULL(@ChargeDiscountAsProduct,0)=0 SET @ChargeDiscountAsProduct = 0

SELECT @PackagesplitAfterDiscount = CONVERT(BIT, KeyValue) FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'PackageSplitAfterDiscount'
SET @PackagesplitAfterDiscount = ISNULL(@PackagesplitAfterDiscount, 0)

SELECT TOP 1 @FK_LogiDepartment = PK_Department 
FROM Departments WITH (NOLOCK)
WHERE AutoCharge = 1 
AND ISNULL(MarkAsDeleted, 0) = 0

IF ISNULL(@FK_LogiDepartment, 0) = 0
BEGIN
  SELECT TOP 1 @FK_LogiDepartment = PK_Department 
  FROM Departments WITH (NOLOCK)
  WHERE ISNULL(MarkAsDeleted, 0) = 0
END

DECLARE @BudgetExtra INT
  
SELECT @BudgetExtra = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'BudgetExtra'
SET @BudgetExtra = ISNULL(@BudgetExtra, 1)

Declare @ValueType tinyint
Set @ValueType = 1 -- skal ændres når conference line medtages

DECLARE @cnt INT

CREATE TABLE #DayProduct (
  Id INT PRIMARY KEY IDENTITY (1, 1), 
  PriceOverwritten BIT, 
  FirstPrice SMALLMONEY NULL, 
  DayCount SMALLINT, 
  ProductNumber INT NULL, 
  GetVatValueFromProduct BIT,
  vatValueRoomProduct FLOAT NOT NULL DEFAULT 0, 
  PriceProduct MONEY NOT NULL DEFAULT 0,
  PackagePriceProduct MONEY NOT NULL DEFAULT 0,
  VatByPacketValueProduct MONEY NOT NULL DEFAULT 0,
  AddOn MONEY NOT NULL DEFAULT 0,
  SplitBill INT NULL
)

CREATE TABLE #ReferenceTable(ReferenceNumber INT NOT NULL)

DECLARE @tmpString VARCHAR(20)
DECLARE @DeleteDateStored DATETIME

SELECT @tmpString=IsNull(KeyValue,0) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey='ReservationsDeletedBefore'
IF ISNULL(@tmpString, 0) = 0
  SET @DeleteDateStored = NULL
ELSE
BEGIN
  SET @DeleteDateStored = CONVERT(DATETIME, @tmpString, 112)
  IF  CONVERT(DATETIME, @CalcForecastFromDate, 112) < @DeleteDateStored
    SET @CalcForecastFromDate = CONVERT(CHAR(8), @DeleteDateStored, 112)
END

Delete from ForecastDaily where Date >= @CalcForecastFromDate 

Declare @RoomReservations smallint 
Set @RoomReservations = 1

While @RoomReservations > -1
begin
  if @RoomReservations = 1
  begin
    IF @ShowPrint = 1
      Print '[[[[[ Room ]]]]]'

    SET @GenerateDayProduct = 0
    Declare ReservationCur Cursor Fast_Forward Read_only For
    SELECT DISTINCT
      isnull(RESERVATIONROOMLINE.LINENUMBER,0),
--      isnull(RESERVATIONROOMLINE.BookedTypeNumber,0),
      isnull(Rooms.Roomtypenumber, RESERVATIONROOMLINE.BookedTypeNumber),
      isnull(RESERVATIONROOMLINE.RoomNumber,0),
      RESERVATIONROOMLINEXTAB.ReferenceNumber,
      RESERVATIONROOMLINEXTAB.GuestNumber,
      RESERVATIONS.Status,
      RESERVATIONS.MARKETSEGMENT,
      RESERVATIONS.POINTOFSALE,
      RESERVATIONROOMLINE.ArrivalDate as ArrivalDate,
      RESERVATIONROOMLINE.DepartureDate as DepartureDate,
      RESERVATIONROOMLINE.DepartureTime,
      ISNULL(RESERVATIONROOMLINE.Adults, 0),
      ISNULL(RESERVATIONROOMLINE.Children1, 0),
      ISNULL(RESERVATIONROOMLINE.Children2, 0),
      ISNULL(RESERVATIONROOMLINE.Adults, 0),
      ISNULL(RESERVATIONROOMLINE.Children1, 0),
      ISNULL(RESERVATIONROOMLINE.Children2, 0),
      RESERVATIONROOMLINE.ProductNumber,
      RESERVATIONROOMLINE.NumberOfRooms,
      isnull(RESERVATIONROOMLINE.Price,0) as Price,
      isnull(RESERVATIONROOMLINE.PriceOverwritten,0) as PriceOverwritten,
      isnull(RESERVATIONROOMLINE.FirstPrice1,0) as FirstPrice1,
      isnull(RESERVATIONROOMLINE.PriceOverwritten2,0) as PriceOverwritten2,
      isnull(RESERVATIONROOMLINE.FirstPrice2,0) as FirstPrice2,
      isnull(RESERVATIONROOMLINE.Day2,0) as Day2,
      isnull(RESERVATIONROOMLINE.ProductNumber2,0) as ProductNumber2,
      isnull(RESERVATIONROOMLINE.PriceOverwritten3,0) as PriceOverwritten3,
      isnull(RESERVATIONROOMLINE.FirstPrice3,0) as FirstPrice3,
      isnull(RESERVATIONROOMLINE.Day3,0) as Day3,
      isnull(RESERVATIONROOMLINE.ProductNumber3,0) as ProductNumber3,
      isnull(RESERVATIONROOMLINE.PriceOverwritten4,0) as PriceOverwritten4,
      isnull(RESERVATIONROOMLINE.FirstPrice4,0) as FirstPrice4,
      isnull(RESERVATIONROOMLINE.Day4,0) as Day4,
      isnull(RESERVATIONROOMLINE.ProductNumber4,0) as ProductNumber4,
      Case when RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER>0 then 1 else 0 end,
      Case when RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER>0 then 1 else 0 end,
      isnull(Customer.CustomerNumber,-1) as CustomerNumber,
      isnull(RESERVATIONROOMLINE.NameListSetting,0),
      RESERVATIONS.SplitBill,
      ReservationRoomLine.SplitBillNumber1,
      ReservationRoomLine.SplitBillNumber2,
      ReservationRoomLine.SplitBillNumber3,
      ReservationRoomLine.SplitBillNumber4
    FROM RESERVATIONROOMLINE WITH (NOLOCK) 
    INNER JOIN RESERVATIONROOMLINEXTAB WITH (NOLOCK) ON RESERVATIONROOMLINE.LINENUMBER = RESERVATIONROOMLINEXTAB.LINENUMBER 
      AND RESERVATIONROOMLINEXTAB.Referencenumber>0 
      AND RESERVATIONROOMLINEXTAB.GuestNumber = 0
      AND RESERVATIONROOMLINE.DepartureDate >= @FormatedStartDate
    INNER JOIN RESERVATIONS WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.ReferenceNumber = RESERVATIONS.ReferenceNumber AND RESERVATIONROOMLINEXTAB.GuestNumber = RESERVATIONS.GuestNumber
      AND ((@IncludeTentative = 0 AND RESERVATIONS.Status in (0,1,2,5,6)) OR (@IncludeTentative = 1 AND RESERVATIONS.Status in (0,1,2,4,5,6)))
    Left Outer Join RESERVATIONCONFERENCELINE WITH (NOLOCK) ON RESERVATIONS.ReferenceNumber=RESERVATIONCONFERENCELINE.ReferenceNumber
    INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.ReferenceNumber = RESERVATIONS.ReferenceNumber
    Left outer join  Customer WITH (NOLOCK) ON isnull(RESERVATIONMAIN.HotelNumber,0) = Customer.HotelNumber AND Customer.HotelNumber>=0 
      AND Customer.CustomerTypeNumber = 7 AND @CentralBookingType = 7 AND ISNULL(Customer.MarkAsDeleted, 0) = 0
    Left outer join Rooms WITH (NOLOCK) on Rooms.roomnumber = RESERVATIONROOMLINE.RoomNumber
    WHERE ISNULL(@DebugReferenceNumber, -1) = -1 OR ReservationRoomLineXTab.ReferenceNumber = @DebugReferenceNumber

    UNION ALL

    SELECT DISTINCT
      isnull(RESERVATIONROOMLINE.LINENUMBER,0),
      isnull(Rooms.Roomtypenumber,RESERVATIONROOMLINE.BookedTypeNumber) as BookedTypeNumber, 
      isnull(RESERVATIONROOMLINE.RoomNumber,0),
      Reservations.ReferenceNumber,
      Reservations.GuestNumber,
      Reservations.Status,
      Reservations.MARKETSEGMENT,
      Reservations.POINTOFSALE,
      Reservations.ArrivalDate as ArrivalDate,
      Reservations.DepartureDate as DepartureDate,
      Reservations.DepartureTime,
      ISNULL(Reservations.Adults, 0),
      ISNULL(Reservations.Children1, 0),
      ISNULL(Reservations.Children2, 0),
      ISNULL(Reservations.PaysAdults, 0),
      ISNULL(Reservations.PaysChildren1, 0),
      ISNULL(Reservations.PaysChildren2, 0),
      Reservations.ProductNumber,
      RESERVATIONROOMLINE.NumberOfRooms,
      isnull(Reservations.Price,0) as Price,
      isnull(Reservations.PriceOverwritten,0) as PriceOverwritten,
      isnull(Reservations.FirstPrice1,0) as FirstPrice1,
      isnull(Reservations.PriceOverwritten2,0) as PriceOverwritten2,
      isnull(Reservations.FirstPrice2,0) as FirstPrice2,
      isnull(Reservations.Day2,0) as Day2,
      isnull(Reservations.ProductNumber2,0) as ProductNumber2,
      isnull(Reservations.PriceOverwritten3,0) as PriceOverwritten3,
      isnull(Reservations.FirstPrice3,0) as FirstPrice3,
      isnull(Reservations.Day3,0) as Day3,
      isnull(Reservations.ProductNumber3,0) as ProductNumber3,
      isnull(Reservations.PriceOverwritten4,0) as PriceOverwritten4,
      isnull(Reservations.FirstPrice4,0) as FirstPrice4,
      isnull(Reservations.Day4,0) as Day4,
      isnull(Reservations.ProductNumber4,0) as ProductNumber4,
      Case when RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER>0 then 1 else 0 end,
      Case when RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER>0 then 1 else 0 end,
      isnull(Customer.CustomerNumber,-1) as CustomerNumber,
      isnull(RESERVATIONROOMLINE.NameListSetting,0),
      RESERVATIONS.SplitBill,
      Reservations.SplitBillNumber1,
      Reservations.SplitBillNumber2,
      Reservations.SplitBillNumber3,
      Reservations.SplitBillNumber4
    FROM RESERVATIONROOMLINE WITH (NOLOCK) 
    INNER JOIN RESERVATIONROOMLINEXTAB WITH (NOLOCK) ON RESERVATIONROOMLINE.LINENUMBER = RESERVATIONROOMLINEXTAB.LINENUMBER 
      AND RESERVATIONROOMLINEXTAB.ReferenceNumber>0 
      AND RESERVATIONROOMLINEXTAB.GuestNumber>0 
      AND RESERVATIONROOMLINE.DepartureDate >= @FormatedStartDate
    INNER JOIN RESERVATIONS WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.ReferenceNumber = RESERVATIONS.ReferenceNumber 
      AND RESERVATIONROOMLINEXTAB.GuestNumber = RESERVATIONS.GuestNumber
      AND RESERVATIONS.GuestNumber > 0 
      AND ((@IncludeTentative = 0 AND RESERVATIONS.Status in (0,1,2,5,6)) OR (@IncludeTentative = 1 AND RESERVATIONS.Status in (0,1,2,4,5,6)))
    Left Outer Join RESERVATIONCONFERENCELINE WITH (NOLOCK) ON RESERVATIONS.ReferenceNumber=RESERVATIONCONFERENCELINE.ReferenceNumber
    INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.ReferenceNumber = RESERVATIONS.ReferenceNumber
    Left outer join  Customer WITH (NOLOCK) ON isnull(RESERVATIONMAIN.HotelNumber,0) = Customer.HotelNumber 
      AND Customer.HotelNumber>=0 AND Customer.CustomerTypeNumber = 7 AND @CentralBookingType = 7 AND ISNULL(Customer.MarkAsDeleted, 0) = 0
    Left outer join Rooms WITH (NOLOCK) on Rooms.roomnumber = RESERVATIONROOMLINE.RoomNumber
    WHERE ISNULL(@DebugReferenceNumber, -1) = -1 OR ReservationRoomLineXTab.ReferenceNumber = @DebugReferenceNumber

    ORDER BY isnull(RESERVATIONROOMLINE.LINENUMBER,0), ArrivalDate, DepartureDate desc, RESERVATIONROOMLINEXTAB.GuestNumber-- VIGTIG (PREVLineNumber<>LineNumber)    

    Open ReservationCur

    Fetch Next From ReservationCur Into @LINENUMBER, @BookedTypeNumber, @RoomNumber, @ReferenceNumber, @GuestNumber, @Status, @SegmentNumber, @PointOfSaleNumber, @ArrivalDate, @DepartureDate, @DepartureTime, 
      @Adults, @Children1, @Children2, @PaysAdults, @PaysChildren1, @PaysChildren2, @ProductNumber, @NumberOfRooms, @Price, @PriceOverwritten, @FirstPrice1,@PriceOverwritten2,@FirstPrice2, @Day2, @ProductNumber2, @PriceOverwritten3,@FirstPrice3, @Day3, @ProductNumber3,
      @PriceOverwritten4, @FirstPrice4, @Day4, @ProductNumber4, @ConferenceLineOnRes, @ConflineOnMainRes, @HotelCustomerNumber, @NameListSetting, 
      @SplitBillNumber, @SplitBillNumber1, @SplitBillNumber2, @SplitBillNumber3, @SplitBillNumber4
  end
  else
  begin
    IF @ShowPrint = 1
      Print '[[[[[ Conf ]]]]]'

    SET @GenerateDayProduct = 1
    Declare ReservationCur Cursor Fast_Forward Read_only For
    SELECT DISTINCT
      RESERVATIONConferenceLINE.BookedConferenceRoomTypeNumber,
      RESERVATIONConferenceLINE.ReservationConfLineNumber,
      RESERVATIONConferenceLINE.ConferenceRoomNumber,
      RESERVATIONConferenceLINE.ArrivalDate,
      RESERVATIONConferenceLINE.DepartureDate,
      RESERVATIONConferenceLINE.ProductNumber,
      RESERVATIONConferenceLINE.NumberOfRooms,
      RESERVATIONS.Status,
      ISNULL(RESERVATIONConferenceLINE.PriceOverWritten,0),
      ISNULL(RESERVATIONConferenceLINE.Adults, 0),
      ISNULL(RESERVATIONConferenceLINE.Children1, 0),
      ISNULL(RESERVATIONConferenceLINE.Children2, 0),
      RESERVATIONConferenceLINE.Price,
      RESERVATIONConferenceLINE.ReferenceNumber,
      RESERVATIONConferenceLINE.PackageNumber,
      RESERVATIONConferenceLINE.ArrivalTime,
      RESERVATIONConferenceLINE.DepartureTime,
      isnull(Customer.CustomerNumber,-1),
      ReservationConferenceLine.FK_ChargeDepartment,
      RESERVATIONS.SplitBill
    from RESERVATIONConferenceLINE WITH (NOLOCK) 
    INNER JOIN Reservations WITH (NOLOCK) ON Reservations.ReferenceNumber=RESERVATIONConferenceLINE.ReferenceNumber 
      AND ((@IncludeTentative = 0 AND RESERVATIONS.Status in (0,1,2,5,6)) OR (@IncludeTentative = 1 AND RESERVATIONS.Status in (0,1,2,4,5,6)))
      AND RESERVATIONS.ReferenceNumber>0 
      AND RESERVATIONConferenceLINE.DepartureDate >= @FormatedStartDate
    INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.ReferenceNumber = RESERVATIONS.ReferenceNumber
    Left outer join Customer WITH (NOLOCK) ON isnull(RESERVATIONMAIN.HotelNumber,0) = Customer.HotelNumber 
      AND Customer.HotelNumber>=0 AND Customer.CustomerTypeNumber = 7 AND @CentralBookingType = 7 AND ISNULL(Customer.MarkAsDeleted, 0) = 0
    WHERE ISNULL(@DebugReferenceNumber, -1) = -1 OR RESERVATIONConferenceLINE.ReferenceNumber = @DebugReferenceNumber
    order by RESERVATIONConferenceLINE.Referencenumber, RESERVATIONConferenceLINE.ReservationConfLineNumber

    Open ReservationCur
    Fetch Next From ReservationCur Into @BookedTypeNumber, @LINENUMBER, @RoomNumber, @ArrivalDate, @DepartureDate, @ProductNumber, @NumberOfRooms,
      @Status,@PriceOverWritten, @Adults, @Children1, @Children2, @Price, @ReferenceNumber, @PacketNumberReservation, @ArrArrivalTime, 
      @ArrDepartureTime, @HotelCustomerNumber, @FK_ChargeDepartment, @SplitBillNumber
  end

  Declare @ProductStartDate DateTime
  Declare @ProductEndDate DateTime
  DECLARE @AddonStartDate DATETIME
  DECLARE @AddonEndDate DATETIME
  Declare @CurrentDate DateTime
  DECLARE @AddonCurrentDate DATETIME
  DECLARE @AddonCurrentDateStr CHAR(8)
  Declare @CurrentDateStr Char(8)
  DECLARE @TempCurrentDateStr CHAR(8)
  DECLARE @DiscountCurrentDate CHAR(8)

  Declare @AddonIfPriceOverwritten bit
  Select @AddonIfPriceOverwritten = isnull(CONVERT(Bit,KeyValue),0) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='AddonIfPriceOverwritten'

  -- Cur: DayProduct Vars
  Declare @GetVatValueFromProduct  Bit
  Declare @GetVatValueFromProduct2  Bit
  Declare @VatValueRoomProduct1 Float
  Declare @VatValueRoomProduct2 Float
  -- SP: ProductPricesDay
  Declare @BillTextProduct VARCHAR(50)
  Declare @BillTextAddOnProduct  VARCHAR(50)
  Declare @PriceProduct1 Money
  DECLARE @tmpPrice MONEY
  Declare @PriceProduct2 Money
  Declare @PackagePriceProduct1 Money
  Declare @VatByPacketValueProduct1 Money
  Declare @StayPacketNumber int
  Declare @PacketNumber int
  Declare @EnviromentFee Money
  Declare @FixedPrice Bit
  Declare @VATProduct Bit
  Declare @SpecifiedDepartureAddOn bit

  DECLARE @DummyBillTextProduct VARCHAR(50)
  DECLARE @DummyBillTextAddOnProduct  VARCHAR(50)
  DECLARE @DummyPriceProduct1 MONEY
  DECLARE @DummyPacketNumber INT
  DECLARE @DummyEnviromentFee MONEY
  DECLARE @DummyVATProduct BIT
  DECLARE @DummySpecifiedDepartureAddOn bit

  Declare @Addon Money
  Declare @Addon1 Money

  Declare @WareNumber Integer
  Declare @BalanceAccountNumber Integer -- Not used but needed by SP
  Declare @ResultAccountNumber Int
  Declare @VATAccountNumber Integer
  Declare @WareText VARCHAR(30)

  Declare @PrevLineNumber Integer
  SET @PrevLineNumber = 0
 
  Declare @PrevReferenceNumber int

  SET @PrevReferenceNumber = 0

  Declare @PrevGuestNumber Integer
  Set @PrevGuestNumber = 0

  Declare @TotalAdults integer
  Declare @TotalChildren1 integer
  Declare @TotalChildren2 integer
  Declare @PackageAccount integer

  DECLARE @tmpPrice1 MONEY 
  
  While  (@@FETCH_STATUS <> -1)
  begin
    IF @RoomReservations = 1
      SET @FK_ChargeDepartment = 0
    
    IF @CentralBookingType = 7
    BEGIN
      IF @RoomReservations = 0 
      BEGIN
        SELECT TOP 1 @tmpDepartment = PK_Department FROM Departments d WITH (NOLOCK)
        INNER JOIN ReservationMain r WITH (NOLOCK) ON d.HotelNumber = r.HotelNumber AND AutoCharge = 1 AND ISNULL(MarkAsDeleted, 0) = 0 AND ReferenceNumber = @ReferenceNumber
      END
      ELSE
      BEGIN
        SELECT TOP 1 @tmpDepartment = PK_Department
        FROM Departments d WITH (NOLOCK)
        INNER JOIN RoomTypes rt WITH (NOLOCK) ON rt.HotelNumber = d.HotelNumber
          AND rt.RoomTypeNumber = @BookedTypeNumber
        WHERE AutoCharge = 1
      END
      IF ISNULL(@tmpDepartment, 0) > 0
        SET @TheDepartmentNumber = @tmpDepartment
      ELSE
        SET @TheDepartmentNumber = @FK_LogiDepartment
    END
    ELSE
      SET @TheDepartmentNumber = @FK_LogiDepartment

    IF ISNULL(@FK_ExDepartment, 0) = 0
      SET @FK_ExDepartment = @TheDepartmentNumber
    IF ISNULL(@FK_ChargeDepartment, 0) = 0
      SET @FK_ChargeDepartment = @TheDepartmentNumber

    if ((@Day2+@Day3+@Day4)>0) or (@ProductNumber>0 and @GuestNumber>0)
      Select @NameListSetting = isnull(NameListSetting,0) from ReservationRoomLine WITH (nolock) where LineNumber = @LINENUMBER
    else if @ProductNumber >0 
      Select @NameListSetting = isnull(NameListSetting,0) from Products WITH (nolock) where productnumber = @ProductNumber
    else
      set @NameListSetting = @NameListSettingHotelSetup

    if (@GetVATFrom=0) -- Get Vat From Segment
      Exec GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @SegmentNumber, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT , @VatValueRoomProduct1 OUTPUT, @WareText OUTPUT
    else if (@GetVATFrom=1) -- Get Vat From POS
      Exec GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @PointOfSaleNumber, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT , @VatValueRoomProduct1 OUTPUT, @WareText OUTPUT
    else if (@GetVATFrom=2) -- Get Vat From Roomtype -- TODO ConferenceRoom if DayProduct
      Exec GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @BookedTypeNumber, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT , @VatValueRoomProduct1 OUTPUT, @WareText OUTPUT

    SET @VatValueWare = @VatValueRoomProduct1

    IF @Day2 <> 0
      SET @SplitBillNumber = @SplitBillNumber1
    insert into #DayProduct(priceOverwritten, firstPrice, dayCount, productNumber, GetVatValueFromProduct, SplitBill) values (ISNULL(@PriceOverwritten,0), @FirstPrice1, 1,     @ProductNumber, 0, @SplitBillNumber)
    
    if @day2<>0 insert into #DayProduct(priceOverwritten, firstPrice, dayCount, productNumber, GetVatValueFromProduct, Splitbill) values (ISNULL(@PriceOverwritten2,0),@FirstPrice2, @Day2, @ProductNumber2, 0, @SplitBillNumber2)
    if @day3<>0 insert into #DayProduct(priceOverwritten, firstPrice, dayCount, productNumber, GetVatValueFromProduct, Splitbill) values (ISNULL(@PriceOverwritten3,0),@FirstPrice3, @Day3, @ProductNumber3, 0, @SplitBillNumber3)
    if @day4<>0 insert into #DayProduct(priceOverwritten, firstPrice, dayCount, productNumber, GetVatValueFromProduct, Splitbill) values (ISNULL(@PriceOverwritten4,0),@FirstPrice4, @Day4, @ProductNumber4, 0, @SplitBillNumber4)

    IF @ShowPrint = 1        
      SELECT * FROM #DayProduct

    if convert(DateTime,@ArrivalDate) < Convert(DateTime,@FormatedStartDate)
      SET @CurrentDateStr = @FormatedStartDate
    else  
      Set @CurrentDateStr = @ArrivalDate
    Set @CurrentDate = Convert(DATETIME, @CurrentDateStr)

    if (@GuestNumber>0 and @NameListSetting=0) OR @RoomReservations = 0
    Begin
      SET @PaysAdults = @Adults
      SET @PaysChildren1 = @Children1
      SET @PaysChildren2 = @Children2
    end

    DECLARE @IsPlusProduct INT
    SELECT @IsPlusProduct = COUNT(*) FROM #DayProduct

    Declare @curDPID1 INT
    Declare @curDPID2 INT

    DECLARE DayProductCur CURSOR FORWARD_ONLY KEYSET FOR
      SELECT id, priceOverwritten, firstPrice, dayCount, productNumber, GetVatValueFromProduct, vatValueRoomProduct, priceProduct, SplitBill FROM #DayProduct
    OPEN DayProductCur
    FETCH NEXT FROM DayProductCur INTO @curDPID1, @PriceOverwritten, @FirstPrice1, @Day, @ProductNumber, @GetVatValueFromProduct, @vatValueRoomProduct1, @priceProduct2, @SplitBillNumber
        
    Set @PriceProduct1=0

    Declare @TmpFetch int
    Set @TmpFetch = @@FETCH_STATUS 

    WHILE @TmpFetch <> -1 
    BEGIN
      FETCH NEXT FROM DayProductCur INTO @curDPID2, @PriceOverwritten2, @FirstPrice2, @Day2, @ProductNumber2, @GetVatValueFromProduct2, @vatValueRoomProduct2, @priceProduct2

      Set @TmpFetch = @@FETCH_STATUS
      Set @ProductStartDate = Convert(DATETIME, @ArrivalDate)+ISNULL(@Day, 0)-1

      IF @TmpFetch <>-1 and isnull(@Day2,0) <> 0
        Set @ProductEndDate = Convert(DATETIME, @ArrivalDate)+@Day2-2
      ELSE IF @IsPlusProduct > 1
        Set @ProductEndDate = Convert(DATETIME, @DepartureDate)-1
      ELSE
        Set @ProductEndDate = Convert(DATETIME, @DepartureDate)
            
      IF @IsPlusProduct > 1
      BEGIN
        SET @AddonStartDate = Convert(DATETIME, @ArrivalDate)+ISNULL(@Day, 0)-1

        IF @TmpFetch <> -1 AND ISNULL(@Day2,0) <> 0
          SET @AddonEndDate = CONVERT(DATETIME, @ArrivalDate)+@Day2-1
        ELSE IF @IsPlusProduct > 1
          SET @AddonEndDate = CONVERT(DATETIME, @DepartureDate)
        ELSE
          SET @AddonEndDate = CONVERT(DATETIME, @DepartureDate)+1
      END

      Declare @PackagePrice Float
      Declare @VatOfPrice money
      Declare @VatOfPacket money
      DEclare @DatePrice money

      IF @ShowPrint = 1
      BEGIN
        PRINT '********************************************'
        PRINT @ReferenceNumber
        PRINT @RoomReservations
        PRINT @CurrentDate 
        PRINT @ProductStartDate
        PRINT @ProductEndDate
        PRINT @AddonStartDate
        PRINT @AddonEndDate
      END

      IF @Arr24 > @ArrDepartureTime
        SET @ProductEndDate = CONVERT(CHAR(8), CONVERT(DATETIME, @ProductEndDate) - 1,112)

      While @CurrentDate <= @ProductEndDate
      begin
        IF @ShowPrint = 1
        BEGIN   
          PRINT '@Price'
          PRINT CONVERT(VARCHAR(10), @Price)
          PRINT '@CurrentDate'
          PRINT CONVERT(VARCHAR, @CurrentDate)
        END

        SET @GenerateDayProduct = ISNULL(@GenerateDayProduct, 0)
        IF @GenerateDayProduct = 1
          SET @OnePersonPaysForAll = NULL
      
        exec ProductPricesDay @ProductNumber, @ArrivalDate, @DepartureDate, @CurrentDate, @BookedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT,  @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll, 0, @GenerateDayProduct

        -- Calc only addon....
        IF @IsPlusProduct > 1
        BEGIN
          SET @AddonCurrentDate = @CurrentDate + 1
          EXEC ProductPricesDay @ProductNumber, @AddonStartDate, @AddonEndDate, @AddonCurrentDate, @BookedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon1 OUTPUT, @DummyBillTextProduct OUTPUT, @DummyBillTextAddOnProduct OUTPUT,  @DummyPriceProduct1 OUTPUT, @PacketNumber OUTPUT, @DummyEnviromentFee OUTPUT, @IsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll, 0, @GenerateDayProduct
        END

        IF @ShowPrint = 1
        BEGIN
          PRINT '---------------------------------'
          PRINT '@CurrentDate'
          PRINT @CurrentDate
          PRINT '@Addon1'
          PRINT CONVERT(VARCHAR(20), @Addon1)
          PRINT '@BillTextAddOnProduct'
          PRINT @BillTextAddOnProduct 
          PRINT '@PriceProduct1' 
          PRINT CONVERT(VARCHAR(20), @PriceProduct1)
          PRINT '@PacketNumber' 
          PRINT @PacketNumber 
          PRINT '@EnviromentFee'
          PRINT CONVERT(VARCHAR(20), @EnviromentFee)
          PRINT '@FixedPrice' 
          PRINT @FixedPrice 
          PRINT '@VATProduct' 
          PRINT @VATProduct 
          PRINT '@SpecifiedDepartureAddOn'
          PRINT @SpecifiedDepartureAddOn
          PRINT '@PaysAdults'
          PRINT @PaysAdults
          PRINT '@ProductNumber'
          PRINT @ProductNumber
        END

        IF @GenerateDayProduct = 1 AND ISNULL(@ProductNumber, 0) <= 0
          SET @PacketNumber = 0          

        if (isnull(@PacketNumber,0)>0)
        begin
          IF @ShowDebug = 1
          BEGIN
            IF @CurrentDateStr >= @DebugStartDate AND @CurrentDateStr <= @DebugEndDate
              PRINT @ReferenceNumber
          END

          SET @tmpPrice1 = 0
          IF @RoomReservations = 0
          BEGIN
            if isnull(@FirstPrice1,0) > 0
              SET @tmpPrice1 = @FirstPrice1 * @NumberOfRooms
            else
              SET @tmpPrice1 = @Price * @NumberOfRooms

            IF @FixedPrice = 0
              SET @tmpPrice1 = @tmpPrice1 * (@Adults+@Children1+@Children2)
          END
          ELSE
            SET @tmpPrice1 = @Price

          EXEC GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 0,  @AllDiscountRate OUTPUT
	
          IF @RoomReservations=1
          BEGIN
            EXEC GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 1, @DiscountRate OUTPUT

            IF @PackagesplitAfterDiscount = 1
              SET @DiscountValue = @DiscountRate + @AllDiscountRate
            ELSE
              SET @DiscountValue = 0
          END

          if  NOT (ISNULL(@DiscountValue, 0) > 0 AND ((@DiscountAsNettoPrice=0) OR (@DiscountAsNettoPrice=1)))
            SET @DiscountValue = 0

          IF @IsPlusProduct > 1
          BEGIN
            SET @AddonCurrentDateStr = CONVERT(CHAR(8), @AddonCurrentDate, 112)
            EXEC CalcPacketPriceAccExt @GenerateDayProduct, @BookedTypeNumber, @AddonCurrentDateStr, @PacketNumber, @ProductNumber, @PaysAdults, @PaysChildren1, @PaysChildren2, @NumberOfRooms, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @NameListSetting, @OnePersonPaysForAll, 1, @PriceOverwritten, @FixedPrice, @TheDepartmentNumber, @ReferenceNumber, @GuestNumber, @tmpPrice1, 0, @DiscountValue
          END  
          ELSE
            EXEC CalcPacketPriceAccExt @GenerateDayProduct, @BookedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber, @PaysAdults, @PaysChildren1, @PaysChildren2, @NumberOfRooms, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @NameListSetting, @OnePersonPaysForAll, 1, @PriceOverwritten, @FixedPrice, @TheDepartmentNumber, @ReferenceNumber, @GuestNumber, @tmpPrice1, 0, @DiscountValue

          IF @ShowPrint = 1
          BEGIN
            PRINT '@CurrentDateStr'
            PRINT @CurrentDateStr
            PRINT '@priceProduct1'
            PRINT CONVERT(VARCHAR(20), @PriceProduct1)
            PRINT '@price'
            PRINT CONVERT(VARCHAR(20), @Price)
            PRINT '@FirstPrice1'
            PRINT CONVERT(VARCHAR(20), @FirstPrice1)
            PRINT '@PackagePriceProduct1'
            PRINT CONVERT(VARCHAR(20), @PackagePriceProduct1)
          END

          Set @priceProduct1 = ISNULL(@priceProduct1, 0) - ISNULL(@PackagePriceProduct1, 0)
        end
        else
          SET @PackagePriceProduct1 = 0

        IF @RoomReservations = 1 AND @PriceOverWritten=0
        BEGIN
          SET @PriceProduct1 = @PriceProduct1 + ISNULL(@Addon1,0)
        END
        ELSE if (@RoomReservations = 1 AND @PriceOverWritten=1) OR (@RoomReservations = 0 AND @Price > 0)
        begin
          IF (((@CurrentDate <= @ProductEndDate) OR (@ArrivalDate = @DepartureDate)) AND @RoomReservations = 1)
          BEGIN
            if isnull(@FirstPrice1,0) > 0
              SET @PriceProduct1 = @FirstPrice1 * @NumberOfRooms
            else
              SET @PriceProduct1 = @Price * @NumberOfRooms

            if @NameListSetting = 1 
              if @OnePersonPaysForAll = 0 
                SET @PriceProduct1 = @PriceProduct1 * (@Adults + @Children1+ @Children2)

            IF @CurrentDate = @ProductEndDate AND ISNULL(@Day2, 0) = 0
              SET @PriceProduct1 = 0

            IF (@AddonIfPriceOverwritten = 1 AND @PriceOverWritten = 1) OR @PriceOverWritten = 0
              SET @PriceProduct1 = @PriceProduct1 + ISNULL(@Addon1,0) - ISNULL(@PackagePriceProduct1,0)
            ELSE
              SET @PriceProduct1 = @PriceProduct1 - ISNULL(@PackagePriceProduct1,0)
          END
          ELSE IF @CurrentDate < @ProductEndDate AND @RoomReservations = 1
          BEGIN
            IF (@AddonIfPriceOverwritten = 1 AND @PriceOverWritten = 1) OR @PriceOverWritten = 0
              SET @PriceProduct1 = ISNULL(@Addon1,0) - ISNULL(@PackagePriceProduct1,0)
            ELSE
              SET @PriceProduct1 = ISNULL(@PackagePriceProduct1,0)
          END 
          ELSE IF @RoomReservations = 0
          BEGIN
            if isnull(@FirstPrice1,0) > 0
              SET @PriceProduct1 = @FirstPrice1 * @NumberOfRooms
            else
              SET @PriceProduct1 = @Price * @NumberOfRooms

            IF @FixedPrice = 0
              SET @PriceProduct1 = @PriceProduct1 * (@Adults+@Children1+@Children2)

            IF (@AddonIfPriceOverwritten = 1 AND @PriceOverWritten = 1) OR @PriceOverWritten = 0
              SET @PriceProduct1 = @PriceProduct1 + ISNULL(@Addon1,0) - ISNULL(@PackagePriceProduct1,0)
            ELSE
              SET @PriceProduct1 = @PriceProduct1 - ISNULL(@PackagePriceProduct1,0)
          END 
        end
        ELSE
          SET @PriceProduct1 = 0

        IF @GetVATFrom IN (3,4)
        BEGIN
          if (@GetVATFrom=3) -- Get Vat From Producttype
          begin
            Exec GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ProductNumber, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT , @VatValueRoomProduct1 OUTPUT, @WareText OUTPUT
          end
          else if (@GetVATFrom=4) -- VAT
          begin
            if @ProductNumber>0
            BEGIN
              Select @VATProduct = abs(0-isnull(ExcludeVAT, 1)) From Products WITH (nolock) WHERE ProductNumber=@ProductNumber
              IF @VATProduct=0 
                SET @VATProduct=1
              ELSE
                SET @VATProduct = 0
            END
            else
              SET @VATProduct = 1
     
            SET @LogiWareIndex = @VATProduct+1
            exec GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @LogiWareIndex, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT , @VatValueRoomProduct1 OUTPUT, @WareText OUTPUT
          end
          SET @VatValueWare = @VatValueRoomProduct1
        END

        SET @CalcDiscount = 1
        IF ISNULL(@PriceProduct1, 0) = 0 AND ISNULL(@Addon1, 0) = 0
          SET @CalcDiscount = 0

        -- Calc Discount
        SET @AllDiscountRate = 0
        SET @DiscountRate = 0

        IF @OrderBookBudgetCalcDiscount = 1 AND @CalcDiscount = 1
        BEGIN
          EXEC FindFolioNumber @ReferenceNumber, @GuestNumber, 0, @WareNumber, @SplitbillNumber, 0, @FolioNumber OUTPUT, @AddressType OUTPUT
 
          EXEC GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 0, @AllDiscountRate OUTPUT
        
          IF @RoomReservations = 1
          BEGIN
            -- ROOM
            EXEC GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 1, @DiscountRate OUTPUT
          END
          ELSE
          BEGIN
            -- HALL
            IF @IsFixedPriceProduct = 1
              EXEC GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 2, @DiscountRate OUTPUT
            ELSE
              EXEC GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 3, @DiscountRate OUTPUT
          END

          IF  (@CurrentDate = CONVERT(DATETIME, @DepartureDate, 112))
            SET @DiscountCurrentDate = CONVERT(CHAR(8), @CurrentDate-1, 112)
          ELSE
            SET @DiscountCurrentDate = CONVERT(CHAR(8), @CurrentDate, 112)
          SET @tmpPrice = @PriceProduct1

          IF @AllDiscountRate>0
          BEGIN
            IF @DiscountAsNettoPrice=0
            BEGIN
              SET @DiscountPrice = Round((@PriceProduct1*(@AllDiscountRate/100)),2)*-1
              IF @ChargeDiscountAsProduct = 0
              BEGIN
                IF @DiscountVatValueWare > 0
                  SET @DiscountPrice = @DiscountPrice-(@DiscountPrice*(1-(1/((@DiscountVatValueWare/100)+1))))
                EXEC UpdateForecast @DiscountResultAccountNumber, @DiscountCurrentDate, @DiscountPrice, @HotelCustomerNumber, @FK_ChargeDepartment, @ReferenceNumber
              END
              ELSE
              BEGIN
                IF @VatValueWare > 0
                  SET @DiscountPrice = @DiscountPrice-(@DiscountPrice*(1-(1/((@VatValueWare/100)+1))))
                EXEC UpdateForecast @ResultAccountNumber, @DiscountCurrentDate, @DiscountPrice, @HotelCustomerNumber, @FK_ChargeDepartment, @ReferenceNumber
              END
            END
            ELSE
              SET @PriceProduct1 = @PriceProduct1-(Round((@tmpPrice*(@AllDiscountRate/100)),2))
          END

          IF @DiscountRate>0
          BEGIN
            IF @DiscountAsNettoPrice=0
            BEGIN
              SET @DiscountPrice = Round((@PriceProduct1*(@DiscountRate/100)),2)*-1

              IF @ChargeDiscountAsProduct = 0
              BEGIN
                IF @DiscountVatValueWare > 0
                  SET @DiscountPrice = @DiscountPrice-(@DiscountPrice*(1-(1/((@DiscountVatValueWare/100)+1))))
                EXEC UpdateForecast @DiscountResultAccountNumber, @DiscountCurrentDate, @DiscountPrice, @HotelCustomerNumber, @FK_ChargeDepartment, @ReferenceNumber
              END
              ELSE
              BEGIN
                IF @VatValueWare > 0
                  SET @DiscountPrice = @DiscountPrice-(@DiscountPrice*(1-(1/((@VatValueWare/100)+1))))
                EXEC UpdateForecast @ResultAccountNumber, @DiscountCurrentDate, @DiscountPrice, @HotelCustomerNumber, @FK_ChargeDepartment, @ReferenceNumber
              END
            END
            ELSE
              SET @PriceProduct1 = @PriceProduct1-(Round((@tmpPrice*(@DiscountRate/100)),2))
          END
        END
        -- Calc Discount END

        IF ISNULL(@VatValueWare,0) > 0
          SET @PriceProduct1 = @PriceProduct1-(@PriceProduct1*(1-(1/((@VatValueWare/100)+1))))

        IF @ShowPrint = 1
        BEGIN
          PRINT '@ResultAccountNumber'
          PRINT @ResultAccountNumber
          PRINT '@PriceProduct1'
          PRINT CONVERT(VARCHAR(19), @PriceProduct1)
        END

        IF @RoomReservations = 0 OR (@CurrentDate < CONVERT(DATETIME, @DepartureDate, 112))
        BEGIN
          IF @ShowDebug = 1
          BEGIN
            IF @CurrentDateStr >= @DebugStartDate AND @CurrentDateStr <= @DebugEndDate
            BEGIN
              PRINT @ReferenceNumber
              PRINT CONVERT(CHAR, @PriceProduct1)
            END
          END

          IF ISNULL(@FK_ChargeDepartment, 0) = 0
            SET @FK_ChargeDepartment = @TheDepartmentNumber            
            
          EXEC UpdateForecast @ResultAccountNumber, @CurrentDateStr, @PriceProduct1, @HotelCustomerNumber, @FK_ChargeDepartment, @ReferenceNumber
        END
        ELSE
        BEGIN
          SET @TempCurrentDateStr = CONVERT(CHAR(8), @CurrentDate-1, 112)

          IF @ShowDebug = 1
          BEGIN
            IF @TempCurrentDateStr >= @DebugStartDate AND @TempCurrentDateStr <= @DebugEndDate
            BEGIN
              PRINT @ReferenceNumber
              PRINT CONVERT(CHAR, @PriceProduct1)
            END
          END

          EXEC UpdateForecast @ResultAccountNumber, @TempCurrentDateStr, @PriceProduct1, @HotelCustomerNumber, @TheDepartmentNumber, @ReferenceNumber
        END
       
        Set @VatOfPrice = 0
        Set @CurrentDate = @CurrentDate +1
        Set @CurrentDateStr = Convert(Char(8), @CurrentDate, 112)
      end

      if isnull(@IncludeDayroomsInSoldRooms,0) = 0 SET @IncludeDayroomsInSoldRooms = 0
      if ((@DayroomsLaterThanTime = '') OR (@DayroomsLaterThanTime is null))  SET @DayroomsLaterThanTime = '13:00'
            
      SET @curDPID1 = @curDPID2
      SET @PriceOverwritten = @PriceOverwritten2
      SET @FirstPrice1 = @FirstPrice2
      SET @Day = @Day2
      SET @ProductNumber = @ProductNumber2
      SET @GetVatValueFromProduct = @GetVatValueFromProduct2
      SET @vatValueRoomProduct1 = @vatValueRoomProduct2
            
      Set @PacketNumber = 0
    END --DayProductCur

    Set @PriceProduct1=0
    Set @FirstPrice1=0
    Set @Day2=0
    Set @Day3=0
    Set @Day4=0
    SET @PriceOverWritten=0
    Set @PackagePriceProduct1=0
    Set @PacketNumber=0

    CLOSE DayProductCur
    DEALLOCATE DayProductCur

    DELETE FROM #DayProduct

    -------------------- Extras BEGIN ---------------------------

    DECLARE @ArrLineNumber INT
    DECLARE @Pieces INT

    SELECT @cnt = COUNT (*) FROM #ReferenceTable WHERE ReferenceNumber = @ReferenceNumber
    IF ISNULL(@cnt, 0) = 0
    BEGIN
      IF @BudgetExtra = 0 -- Include all extras - also without Department
      BEGIN
        Declare ExtraCursor CURSOR Fast_Forward Read_only FOR
          SELECT DISTINCT ArrangementLines.Price, Pieces, ResultAccountNumber, Date, Accounts.VatValueNumber, ArrangementLines.ArrangementLineNumber, ArrangementLines.FK_ExDepartment, ArrangementReservationsXTab.GuestNumber, Ware.WareNumber
          FROM ArrangementLines WITH (NOLOCK) 
          INNER JOIN ArrangementReservationsXTab WITH (NOLOCK) ON arrangementreservationsxtab.Arrangementlinenumber= arrangementlines.arrangementlinenumber 
            AND referencenumber = @ReferenceNumber
            AND ISNULL(TotalPrice,0) <> 0
          INNER JOIN Ware WITH (NOLOCK) ON ArrangementLines.WareNumber = Ware.WareNumber
          INNER JOIN Accounts WITH (NOLOCK) ON Accounts.AccountNumber = Ware.ResultAccountNumber
          LEFT OUTER JOIN Departments d WITH (NOLOCK) ON d.PK_Department = ArrangementLines.FK_ExDepartment
          LEFT OUTER JOIN ArrangementRoomXTab WITH (NOLOCK) ON Arrangementlines.ArrangementLineNumber = ArrangementRoomXtab.ArrangementLineNumber
          WHERE ArrangementRoomXTab.ArrangementLineNumber IS NULL
          AND ISNULL(ArrangementLines.PacketItemNumber, 0) = 0
      END
      ELSE
      BEGIN  -- Only extras on Autocharge department
        Declare ExtraCursor CURSOR Fast_Forward Read_only FOR
          SELECT DISTINCT ArrangementLines.Price, Pieces, ResultAccountNumber, Date, Accounts.VatValueNumber, ArrangementLines.ArrangementLineNumber, ArrangementLines.FK_ExDepartment, ArrangementReservationsXTab.GuestNumber, Ware.WareNumber
          FROM ArrangementLines WITH (NOLOCK) 
          INNER JOIN ArrangementReservationsXTab WITH (NOLOCK) ON arrangementreservationsxtab.Arrangementlinenumber= arrangementlines.arrangementlinenumber 
            AND referencenumber = @ReferenceNumber
            AND NOT ArrangementLines.FK_ExDepartment IS NULL
            AND ISNULL(TotalPrice,0) <> 0
          INNER JOIN Ware WITH (NOLOCK) ON ArrangementLines.WareNumber = Ware.WareNumber
          INNER JOIN Accounts WITH (NOLOCK) ON Accounts.AccountNumber = Ware.ResultAccountNumber
          INNER JOIN Departments d WITH (NOLOCK) ON d.PK_Department = ArrangementLines.FK_ExDepartment
            AND d.AutoCharge = 1
          LEFT OUTER JOIN ArrangementRoomXTab WITH (NOLOCK) ON Arrangementlines.ArrangementLineNumber = ArrangementRoomXtab.ArrangementLineNumber
          WHERE ArrangementRoomXTab.ArrangementLineNumber IS NULL
          AND ISNULL(ArrangementLines.PacketItemNumber, 0) = 0
      END
      
      OPEN ExtraCursor

      FETCH NEXT FROM ExtraCursor INTO @Price, @Pieces, @ResultAccountNumber, @CurrentDateStr, @VatValueNumber, @ArrLineNumber, @FK_ExDepartment, @ExtraGuestNumber, @ExtraWareNumber
 
      While @@FETCH_STATUS <> -1
      Begin
        SET @VatValueWare = CASE @VatValueNumber
          WHEN 1 THEN @VatValueIndex1
          WHEN 2 THEN @VatValueIndex2
          WHEN 3 THEN @VatValueIndex3
          WHEN 4 THEN @VatValueIndex4
          WHEN 5 THEN @VatValueIndex5
        END

        IF ISNULL(@Pieces,0)=0 
          SET @Pieces=0
        IF ISNULL(@Price,0)=0 
          SET @Price=CONVERT(MONEY,0)

        SET @Price=@Price*@Pieces

        SELECT @IsMenuWare = COUNT(*) FROM MenuWareXTab WHERE MenuNumber = @ExtraWareNumber
        IF @IsMenuWare = 1
        BEGIN
          SELECT @SumPercentage = SUM(mw.procentage)
          FROM dbo.ware w WITH (NOLOCK) 
          INNER JOIN dbo.MenuWareXTab mw WITH (NOLOCK) ON w.warenumber = mw.warenumber 
          AND mw.menunumber = @ExtraWareNumber
      
          IF @SumPercentage <> 100
            SET @HandleAsMenuWare = 0
          ELSE
            SET @HandleAsMenuWare = 1
        END
        ELSE
          SET @HandleAsMenuWare = 0

        IF @HandleAsMenuWare = 1
        BEGIN
          -- get the menuwares
          DECLARE db_menuware_cur CURSOR STATIC FOR
            SELECT mw.Procentage, Accounts.VatValueNumber, w.ResultAccountNumber
            FROM Ware w WITH (NOLOCK)          
            INNER JOIN MenuWareXTab mw WITH (NOLOCK) ON w.WareNumber = mw.WareNumber 
              AND mw.MenuNumber = @ExtraWareNumber
            INNER JOIN ACCOUNTS WITH (NOLOCK) ON w.ResultAccountNumber = Accounts.AccountNumber
          OPEN db_menuware_cur

          FETCH NEXT FROM db_menuware_cur INTO @MenuProcentage, @MenuVatValueNumber, @MenuWareResultAccountNumber
          
          WHILE @@FETCH_STATUS = 0
          BEGIN
            EXEC GetVatvalueFromVATValueNumber @MenuVatValueNumber, @MenuVatValueWare OUTPUT
            SET @MenuWarePrice = ((@Price*@MenuProcentage)/100.0)

            IF @OrderBookBudgetCalcDiscount = 1
            BEGIN
              SET @AllDiscountRate = 0
              EXEC FindFolioNumber @ReferenceNumber, @ExtraGuestNumber, 0, @ExtraWareNumber, @SplitbillNumber, 0, @FolioNumber OUTPUT, @AddressType OUTPUT
        
              EXEC GetDiscountRate @ReferenceNumber, @ExtraGuestNumber, @AddressType, 0, @AllDiscountRate OUTPUT
  
              IF @AllDiscountRate>0
              BEGIN
                IF @DiscountAsNettoPrice=0
                BEGIN
                  SET @DiscountPrice = Round((@MenuWarePrice*(@AllDiscountRate/100)),2)*-1
                  IF @DiscountVatValueWare > 0
                    SET @DiscountPrice = @DiscountPrice-(@DiscountPrice*(1-(1/((@DiscountVatValueWare/100)+1))))

                  IF @ChargeDiscountAsProduct = 0
                    EXEC UpdateForecast @DiscountResultAccountNumber, @CurrentDateStr, @DiscountPrice, @HotelCustomerNumber, @FK_ExDepartment, @ReferenceNumber
                  ELSE
                    EXEC UpdateForecast @MenuWareResultAccountNumber, @CurrentDateStr, @DiscountPrice, @HotelCustomerNumber, @FK_ExDepartment, @ReferenceNumber
                END
                ELSE
                  SET @MenuWarePrice = @MenuWarePrice-(Round((@MenuWarePrice*(@AllDiscountRate/100)),2))
              END
            END   

            IF ISNULL(@VatValueNumber, 0) > 0
              SET @MenuWarePrice = @MenuWarePrice-(@MenuWarePrice*(1-(1/((@VatValueWare/100)+1))))
  
            IF ISNULL(@FK_ExDepartment, 0) = 0
              SET @FK_ExDepartment = @TheDepartmentNumber
            EXEC UpdateForecast @MenuWareResultAccountNumber, @CurrentDateStr, @MenuWarePrice, @HotelCustomerNumber, @FK_ExDepartment, @ReferenceNumber
            
            FETCH NEXT FROM db_menuware_cur INTO @MenuProcentage, @MenuVatValueNumber, @MenuWareResultAccountNumber
          END  
          CLOSE db_menuware_cur
          DEALLOCATE db_menuware_cur
        END
        ELSE
        BEGIN
          -- Calc Discount
          IF @OrderBookBudgetCalcDiscount = 1
          BEGIN
            SET @AllDiscountRate = 0
            EXEC FindFolioNumber @ReferenceNumber, @ExtraGuestNumber, 0, @ExtraWareNumber, @SplitbillNumber, 0, @FolioNumber OUTPUT, @AddressType OUTPUT
        
            EXEC GetDiscountRate @ReferenceNumber, @ExtraGuestNumber, @AddressType, 0, @AllDiscountRate OUTPUT

            IF @AllDiscountRate>0
            BEGIN
              IF @DiscountAsNettoPrice=0
              BEGIN
                SET @DiscountPrice = Round((@Price*(@AllDiscountRate/100)),2)*-1
                IF @DiscountVatValueWare > 0
                  SET @DiscountPrice = @DiscountPrice-(@DiscountPrice*(1-(1/((@DiscountVatValueWare/100)+1))))

                IF @ChargeDiscountAsProduct = 0
                  EXEC UpdateForecast @DiscountResultAccountNumber, @CurrentDateStr, @DiscountPrice, @HotelCustomerNumber, @FK_ExDepartment, @ReferenceNumber
                ELSE
                  EXEC UpdateForecast @ResultAccountNumber, @CurrentDateStr, @DiscountPrice, @HotelCustomerNumber, @FK_ExDepartment, @ReferenceNumber
              END
              ELSE
                SET @Price = @Price-(Round((@Price*(@AllDiscountRate/100)),2))
            END
          END  
          -- Calc Discount END
  
          IF ISNULL(@VatValueNumber, 0) > 0
            SET @Price = @Price-(@Price*(1-(1/((@VatValueWare/100)+1))))

          IF ISNULL(@FK_ExDepartment, 0) = 0
            SET @FK_ExDepartment = @TheDepartmentNumber
          EXEC UpdateForecast @ResultAccountNumber, @CurrentDateStr, @Price, @HotelCustomerNumber, @FK_ExDepartment, @ReferenceNumber
        END
        
        FETCH NEXT FROM ExtraCursor INTO @Price, @Pieces, @ResultAccountNumber, @CurrentDateStr, @VatValueNumber, @ArrLineNumber, @FK_ExDepartment, @ExtraGuestNumber, @ExtraWareNumber
      End

      Close ExtraCursor
      Deallocate ExtraCursor

      INSERT INTO #ReferenceTable VALUES (@ReferenceNumber)
    END
    -------------------- Extras END ---------------------------

    if @RoomReservations = 1
    begin
      Fetch Next From ReservationCur Into @LINENUMBER, @BookedTypeNumber, @RoomNumber, @ReferenceNumber, @GuestNumber, @Status, @SegmentNumber, @PointOfSaleNumber, @ArrivalDate, @DepartureDate, @DepartureTime, 
        @Adults, @Children1, @Children2, @PaysAdults, @PaysChildren1, @PaysChildren2, @ProductNumber,@NumberOfRooms, @Price, @PriceOverwritten, @FirstPrice1,@PriceOverwritten2,@FirstPrice2, @Day2, @ProductNumber2, @PriceOverwritten3,@FirstPrice3, @Day3, @ProductNumber3,
        @PriceOverwritten4,@FirstPrice4,@Day4, @ProductNumber4, @ConferenceLineOnRes, @ConflineOnMainRes, @HotelCustomerNumber, @NameListSetting, 
        @SplitBillNumber, @SplitBillNumber1, @SplitBillNumber2, @SplitBillNumber3, @SplitBillNumber4
    end
    else
    begin
      Fetch Next From ReservationCur Into @BookedTypeNumber, @LINENUMBER, @RoomNumber, @ArrivalDate, @DepartureDate, @ProductNumber, @NumberOfRooms,
        @Status,@PriceOverWritten,@Adults, @Children1, @Children2, @Price, @ReferenceNumber, @PacketNumberReservation, @ArrArrivalTime, @ArrDepartureTime, 
        @HotelCustomerNumber, @FK_ChargeDepartment, @SplitBillNumber
    end
  end --outer cursor: ReservationCur

  Close ReservationCur
  Deallocate ReservationCur

  Set @RoomReservations = @RoomReservations-1

  UPDATE Hotelsetup SET KeyValue = @SystemDateStr WHERE Searchkey = 'LastForecastUpdate'
end

DROP TABLE #DayProduct
DROP TABLE #ReferenceTable