CREATE PROCEDURE dbo.GenerateTurnoverMIS @DayProduct BIT = 1
  , --Not used
  @SameVAT BIT
  , --Picasso sends always 0
  @GetVATFrom SMALLINT
  , --HotelSetup BookkeepingReport (0=Segment, 1=POS, 2=Roomtype/HallType, 3=ProductType, 4=?)
  @CalcMISFromDate CHAR(8) = ''
  , -- If used, must be before systemdate
  @DebugReferenceNumber INT = - 1
  , --Calculate a single reservation (can be combined with @CalcOnlyChangedReservations=1)
  @CalcSystemDateOnly BIT = 0
  , @CalcOnlyChangedReservations BIT = 0
  , --Calculate reservations changed since HotelSetup->'LastMISChangedUpdate'
  @CalcMISToDate CHAR(8) = '' --If used, Must be later than @CalcMISFromDate
AS
SET NOCOUNT ON

DECLARE @ShowPrint BIT
SET @ShowPrint = 0

DECLARE @ShowTimeing BIT
SET @ShowTimeing = 0

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 1'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

/*
  Todo:
    SplitBill for +Period

  Uses sp:
	- GetVatValueAndAccountNumbers (bl. momssats)
	- ProductPricesDay
	- CalcPacketPriceAccExt       (Populates #PacketWareTable)
	- GetVatValueFromVatValueNumber
	- UpdateMISTable              (insert into MISTable)
	- MisStoreLogiAndCalcDiscount (calls UpdateMISTable)
	- MisStoreExtrasAndCalcDiscount (insert into MISTable)
	- MisUpdateProductWareLinkNumbers
	- GenerateMISTotals
	- MISCalcProvision
	- MISGenerateAllotment

	Field Room_HallType: 0=Room, 1=Hall, 2=From Room Allotment, 3=No room, no hall 

   Changes:
    KJ 20241009: Ext: Added From/To Time
    KJ 20241008: Bug: Fix for "Wrong hotel number used when charge packet department enabled".
    KJ 20240528: Bug: Fix for "Charge discount as product is default = 1"
    KJ 20240521: Bug: "Fix" for "Arithmetic overflow error converting expression to data type int
    KJ 20240501: Opt: Get transactions for calc takes long time
    KJ 20240501: Ext: Added print of time
    KJ 20240313: Bug: Fix for "Waitinglist reservation is included". Case #CR240657
    KJ 20240312: Bug: Fix for "GuestType not set for table reservations". Case #CR241736
    KJ 20231218: Ext: Added Guesttype, purposeCode and country
    KJ 20231213: Bug: Fix for "TRIM is not a recognized built-in function name". Case #CR238898
    KJ 20231213: Bug: Fix for "Unknown room/hall type".
    KJ 20231113: Bug: Fix for "Wrong status for roomlinelines with different status than reservation".
    KJ 20231024: Bug: Fix for "Wrong hall type". Case #CR237038
    KJ 20230830: Bug: Fix for "Wrong number of rooms if name list per person and one or more lines is cancelled". Case #CR235095
    KJ 20230825: Bug: Fix for "Wrong status for roomlinelines with different status than reservation". Case #CR235100
    KJ 20230508: Bug: Fix for "Reservations not calculated".
    KJ 20230412: Valuetype wrong for discount if ruuning charge discount as product
    SG 20221222: Changed the way it is decided when a res. has room or hall in the transaction section. 
	             NOTE: HallTypeNumber may not always be correct, when there are more than one hallline and same product. 
    SG 20221011: Added support for PlusProductSamePeriod
    SG 20221010: Added @PrevStatus. When 1. guest sharing room with another are NoShow or deleted, the @BookedNumberOfRooms was wrong
    SG 20220929: Format only (Poor mans SQL-formatter)												  
    SG 20220927: Addedsupport for reservations without room or hall. Removed some unused variables
    SG 20220502: Added allotment
    SG 20210413: IsNull(@RoomTypeNumber, 0) added
    SG 20210322: @RoomTypeNumber was not set when grouped by Halltype
    SG 20210309: Ware count (recalc from first day previous year in first nightaudit after update)
    SG 20200611: Halls, fixed price, error in call to CalcPacketPriceAccExt
    SG 20200609: MisStoreExtrasAndCalcDiscount: Don't send Status
    SG 20200525: Store WareNumber and WareType in MISTable
    SG 20200514: Don't include Canceled Online reservations RequestorID = -2 => Online, canceled by service (CreationInProgress = 1)
    SG 20200423: Added provision
    kj 20200414: Bug: Fix for "Incorrect syntax near the keyword 'SELECT'."
    SG 20200408: Include status 7 and 8 in reservations
    SG 20191004: Project primarely from Folios.FkProjectCode in transaction section
    SG 20190710: Removed MISTABLEPackSum.DateStamp!
    SG 20190611: Added MISTABLEPackSum.DateStamp
    SG 20190607: Store Main Course Reservations with 0 values
    SG 20190514: Changed ISNULL(RESERVATIONS.STATUS, -1), to ISNULL(RESERVATIONS.STATUS, 0) as Status, (Arithmetic overflow error for data type tinyint, value = -1)
    SG 20181025: Changes in order to get Mixed Resources correct
    SG 20180514: Date parameters from Picasso may be NULL when @CalcOnlyChangedReservations=1
    SG 20171121: Call to GetVatValueAndAccountNumbers when +product was wrong -> Wrong accountNumber
    SG 20171004: Corrected DELETE FROM MISTABLE. Error: Records from res. back in time holding pieces & pax was deleted, when res was marked changed.
    SG 20171002: Removed @MISOrderbookEarliestRecalcDate. Funktionality fulfilled through fct. GetLatestDeletedBefore. 
    SG 20170928: Added @MISOrderbookEarliestRecalcDate 
    SG 20170921: More and changed logging in MISTotals
    SG 20170904: Booked RoomType / Allocated RoomType from HotelSetup.MISUseBookedRoomType (default 1)
    SG 20170822: Check for CalcMISToDate = NULL (recieve null from Picasso)
    SG 20170808: Transactions.FolioNumber = -1 => FolioNumber -99 in MISTable in order not to be mixed with records from reservations having FolioNumber = -1
    SG 20170629: Added HotelSetup MISCalcRunning
    SG 20170629: Added param @CalcMISToDate. Possible to recalculate in date intervals back in time in order to avoid long calculation duration.
    SG 20170522: Don't recalt res. back in time even if marked changed
    SG 20170515: Changed delete section and WHERE clauses 
    SG 20170404: When calc. only changed, some res. passing date (in #ReservationsCrossDate) was not recalculated. When no res. was changed, records not in a reservation (ref.=-1) was deleted.
    SG 20170217: Conflict of @ProductWareLinkNumber when calculating only changed res. avoided. Check for LastMISChangedUpdate excist changed
    SG 20170131: Recalculation of VAT only for newly recalculated res. when calculation of changed reservations
    KJ 20170120: Opt: MIS recalc is slow.
    SG 20170110: Don't use HotelSetup InternalCourseProduction any more. @MainCourceResNotInclMIS_OrderBook default 0
    SG 20161102: SET LOCK_TIMEOUT 10, logging @CountResToRecalc in MISTotals
    SG 20160929: Calculation of changed reservations. Delete corrected
    KJ 20160909: Moved LastUpdDateStamp from Reservations to ReservationsExt
    SG 20160901: Discount on package
    SG 20160829: Get POS and Segment from customer, when there is no reservation
    SG 20160602: Calculation of changed reservations. @DebugReferenceNumber do not calculate back in time
    KJ 20160418: Implemented MISTotalCalcNeeded
    SG 20160310: Added calculation of changed reservations
    SG 20160310: Format using ApexSQL, FormatSQL, default (plugin to SQL Manager)
    SG 20160226: Wrong no. of params in CalcPacketPriceAccExt (again!)
    SG 20150904: Exec GenerateMISTotals
    SG 20150904: Format using Notepad++, Poor Man's T-SQL formatter
    SG 20150427: Added distinct in Transaction section
    SG 20150331: Main course reservations may not be included (hotelSetup)
    SG 20130911: ProductNumber not set to null even if folio.ReferenceNumber is NULL (eg. when moving to a common folio)
	             This and the ** resets the changes of (OF 20120926). Don't understand the reason?
	SG 20130528: CR 059071, 059428: Input @CalcSystemDateOnly = NULL was not handled
	KJ/SG: 20130515: CalcMISFromDate wrong if running from nightaudit. Case #CR059084
	SG 20130225: Back to version dated 20130208.
	SG 20130208: Error in no. of parameters to CalcPacketPriceAccExt
	SG 20130124: ProductNumber on moved transactions not set to null. **
	SG 20130124: ReservationRoomline.BookedTypeNumber has precedence over Rooms.RoomTypeNumber as in reservation (KA decision).
	SG 20130124: Room-package on departure day comes from transaction and should not be included from reservation.
	SG 20130111, CR 048541 and CR 051014: Transactions, all ProductNumber was set to null.	
	SG 20130107, CR 048684: @TmpProductNumber reset in each loop. When ProductNumber was NULL, we got the value from the previous record with a value not NULL.
	SG 20121228, CR 047175: Parameter PriceOverwritten was missing in calls to CalcPacketPriceAccExt. Param @PriceOverwrittenValue for one room. 
	SG CR 050510: Linking of product and package on SystemDate changed (also MisUpdateProductWareLinkNumbers). 
	OF 20120921: Ext: To many hall lines where produced.
	OF 20120926: Bug: Corrections back in time cannot have productnumbers.
	OF 20120907: Ext: No need to handle extras back in time from reservations.
	OF 20120824: Ext: ProductNumber added to pieces/pax record in transaction part
   	OF 20120806: Ext: Discount trial.
	OF 20120808: Ext: ProductNumber added to mis
 	KJ 20120713: Ext: Forecast calculation is removed.
  	OF 20120712: Ext: Performancetuning on real vat calculation of productprices.
   	OF 20120710: Bug: Addons accidentially landed in actual.
	OF 20120706: Ext: New mis attempt rev. 1
	OF 20120531: Bug: Figures arround system date bug fixed.
	OF 20120530: Ext: SystemDate reintroduced for LastMisUpdate
 	OF 20120502: Ext: OwnerReservation included.
	OF 20120425: Ext: MisTable is now used as detail view for MIS Detail viewer.
	OF 20120419: Bug: Missing arrangementlines. Landed on wrong hotel.
	OF 20120417: Ext: Primary keys removed and detailed mis introduced.

     Use of table MISTotals:
     ======================
     SystemDate    DateStamp    ReferenceNumber   BookedPrice    ActualPrice
     Log at start:
     Systemdate: The real systemdate. DateStamp: 'NORMAL' for a calculation from Picasso date. MMdd from FromDate. MMddMMdd from FromDate and todate. ReferenceNumber = -99
     Systemdate: The real systemdate. DateStamp: 'RECALC'. ReferenceNumber is the number of reservations recalculated because of changes. 0 means all.
     Sums after calculation of all reservations with a datestamp >= startdate:
     Systemdate: Picasso date + real time. Datestamp and ReferenceNumber from reservations. BookedPrice and ActualPrice are sums for each reservation on each day.
*/
SET LOCK_TIMEOUT 10000

DECLARE @cnt INT

SET @DayProduct = 1-- always include conferencereservations  

DECLARE @GenerateDayProduct BIT
DECLARE @DateStamp CHAR(8)
DECLARE @SegmentNumber INT
DECLARE @PointOfSaleNumber INT
DECLARE @GuestType INT
DECLARE @PurposeCode INT
DECLARE @RoomTypeNumber INT
DECLARE @HallTypeNumber INT
DECLARE @BookedNumberOfRooms INT
DECLARE @Adults INT
DECLARE @Children1 INT
DECLARE @Children2 INT
DECLARE @Pieces INT
DECLARE @PaysAdults INT
DECLARE @PaysChildren1 INT
DECLARE @PaysChildren2 INT
DECLARE @TotalAdults INT
DECLARE @TotalChildren1 INT
DECLARE @TotalChildren2 INT
DECLARE @CurrentDateStr CHAR(8)
DECLARE @TempCurrentDateStr CHAR(8)
DECLARE @CurrentDate DATETIME
DECLARE @SystemDateStr CHAR(8)
DECLARE @FormatedStartDate CHAR(8)
DECLARE @SystemDate DATETIME
DECLARE @AllocatedTypeNumber INT
DECLARE @Room_HallType TINYINT--0: Room, 1: Hall, 2: Room allotment, 3: No room, no hall
  -- Declare Reservation Roomline Fields  
DECLARE @LINENUMBER INT
DECLARE @ConferenceLineOnRes BIT
DECLARE @BookedTypeNumber INT
DECLARE @RoomNumber INT
DECLARE @NumberOfRooms SMALLINT
DECLARE @ArrivalDate CHAR(8)
DECLARE @ArrivalTime CHAR(5)
DECLARE @DepartureDate CHAR(8)
DECLARE @DepartureTime CHAR(5)
DECLARE @ProductNumber INT
DECLARE @TmpProductNumber INT
DECLARE @ProductNumberPacket INT
DECLARE @BookedWareCountPacket INT
DECLARE @Price MONEY
DECLARE @TotalPrice MONEY
DECLARE @PriceOverwritten BIT
DECLARE @PriceOverwrittenValue MONEY
DECLARE @Status SMALLINT
DECLARE @ResultAccountNumber INT
DECLARE @ResultAccountPackage INT
DECLARE @DepartmentNumber SMALLINT
DECLARE @DepartmentNumberPackage SMALLINT
DECLARE @VatByPacketValue FLOAT
DECLARE @PackagePrice FLOAT
DECLARE @PacketWarePrice FLOAT
DECLARE @VatOfPacketWarePrice FLOAT
DECLARE @PacketNumber INT
DECLARE @PacketNumberReservation INT
DECLARE @TotalPriceDay MONEY
DECLARE @ProductPriceDate DATETIME
DECLARE @VatValueRoomProduct1 FLOAT
DECLARE @VatValueRoomProduct2 FLOAT
DECLARE @VatValueRoomProduct3 FLOAT
DECLARE @VatValueRoomProduct4 FLOAT
DECLARE @PriceProduct1 MONEY
DECLARE @PriceProduct2 MONEY
DECLARE @PriceProduct3 MONEY
DECLARE @PriceProduct4 MONEY
DECLARE @PackagePriceProduct1 MONEY
DECLARE @PackagePriceProduct2 MONEY
DECLARE @PackagePriceProduct3 MONEY
DECLARE @PackagePriceProduct4 MONEY
DECLARE @VatByPacketValueProduct1 MONEY
DECLARE @VatByPacketValueProduct2 MONEY
DECLARE @VatByPacketValueProduct3 MONEY
DECLARE @VatByPacketValueProduct4 MONEY
DECLARE @FirstFetch BIT
DECLARE @ReferenceNumber INT
DECLARE @FolioNumber INT
DECLARE @GuestNumber INTEGER
DECLARE @PrevLineNumber INTEGER
DECLARE @PrevReferenceNumber INT
DECLARE @PrevGuestNumber INTEGER
DECLARE @SmallestArrivalDate CHAR(8)
DECLARE @BiggestDepartureDate CHAR(8)
DECLARE @PlusProductSamePeriod BIT
DECLARE @Day2 SMALLINT
DECLARE @Day3 SMALLINT
DECLARE @Day4 SMALLINT
DECLARE @ProductNumber2 INTEGER
DECLARE @ProductNumber3 INTEGER
DECLARE @ProductNumber4 INTEGER
DECLARE @PriceOverwritten2 BIT
DECLARE @PriceOverwritten3 BIT
DECLARE @PriceOverwritten4 BIT
DECLARE @FirstPrice1 MONEY
DECLARE @FirstPrice2 MONEY
DECLARE @FirstPrice3 MONEY
DECLARE @FirstPrice4 MONEY
DECLARE @StarProduct BIT-- +Product
DECLARE @ProductStartDate DATETIME
DECLARE @ProductEndDate DATETIME
DECLARE @TmpProductStartDate DATETIME
DECLARE @TmpProductEndDate DATETIME
DECLARE @TableCount SMALLINT-- 1 = Roomline og 2=Confline (hall), 3=NoRoom, no Confline
DECLARE @EnviromentFee MONEY
DECLARE @GetVatValueFromProduct2 BIT
DECLARE @GetVatValueFromProduct3 BIT
DECLARE @GetVatValueFromProduct4 BIT
DECLARE @TotalPackagePrice MONEY
DECLARE @TotalVatByPacketValue MONEY
DECLARE @WareNumber INTEGER
DECLARE @WareNumberProduct INTEGER
DECLARE @WareGroupNumber INTEGER
DECLARE @WareGroupNumberProduct INTEGER
DECLARE @WareName VARCHAR(50)
/* Never used but needed for  SP GetVatValueAndAccountnumbers */
DECLARE @BalanceAccountNumber INTEGER
DECLARE @VATAccountNumber INTEGER
DECLARE @WareText VARCHAR(30)
DECLARE @Addon MONEY
DECLARE @VatOfAddon MONEY
DECLARE @Addon1 MONEY
DECLARE @Addon2 MONEY
DECLARE @Addon3 MONEY
DECLARE @Addon4 MONEY
DECLARE @BillTextProduct VARCHAR(50)
DECLARE @BillTextAddOnProduct VARCHAR(50)
DECLARE @FixedPrice BIT
DECLARE @VATProduct BIT
DECLARE @SpecifiedDepartureAddOn BIT
DECLARE @VatOfPacket MONEY
DECLARE @VatOfPrice MONEY
DECLARE @AddonIfPriceOverwritten BIT--HotelSetup
DECLARE @AddonAsWare BIT --HotelSetup
DECLARE @ChargeAddonAsProduct BIT --HotelSetup
DECLARE @ValueType TINYINT--1: Room, 2:Halls, 3: Day meeting, 4: Restaurant, 5: Other
DECLARE @MisData BIT
DECLARE @Arr24 CHAR(5)
DECLARE @ArrArrivalTime CHAR(5)
DECLARE @ArrDepartureTime CHAR(5)
DECLARE @OldSegmentNumber INT
DECLARE @DefaultMISPointOfSale INT
DECLARE @DefaultMISSegment INT
DECLARE @DefaultMISGuestType INT
DECLARE @DefaultMISPurposeCode INT
DECLARE @NameListSetting TINYINT
DECLARE @NameListSettingHotelSetup TINYINT
DECLARE @WareType INT
DECLARE @OnePersonPaysForAll BIT
DECLARE @IncludeTentative BIT
DECLARE @IncludeDayroomsInSoldRooms BIT
DECLARE @DayroomsLaterThanTime CHAR(5)
DECLARE @ConflineOnMainRes BIT
DECLARE @NightAuditRunning BIT
DECLARE @MISCalcRunning BIT
DECLARE @HotelCustomerNumber INT
DECLARE @LastMISUpdate DATETIME--Updated by nightaudit
DECLARE @LastMISChangedUpdate DATETIME--Updated changed reservations
DECLARE @MISAllotmentEnable BIT
DECLARE @LatestDeletedBefore CHAR(8)
DECLARE @Plenum BIT
DECLARE @PackageSameDayAsLogi BIT
DECLARE @CurrentDateStrDeparturePackage CHAR(8)
DECLARE @tmpUpdateType TINYINT
DECLARE @tmpSameDayAsLogi BIT
DECLARE @CampaignCode SMALLINT
DECLARE @ProjectCode SMALLINT
DECLARE @StaffID INT
DECLARE @IsPackage BIT
DECLARE @ProductWareLinkNumber BIGINT
DECLARE @ProductWareLinkNumberMis BIGINT
DECLARE @ProductWareLinkNumberTrans BIGINT
DECLARE @PackageStored BIT
DECLARE @tmpProductWareLinkNumberTrans BIGINT
DECLARE @tmpProductWareLinkNumberMis BIGINT
DECLARE @Text VARCHAR(100)
DECLARE @OwnerReservation BIT
DECLARE @OrderBookBudgetCalcDiscount BIT
DECLARE @DiscountWareNumber INT
DECLARE @DiscountAsNettoPrice BIT
DECLARE @ChargeDiscountAsProduct BIT
DECLARE @DiscountResultAccountNumber INT
DECLARE @DiscountVatValueWare FLOAT
DECLARE @DiscountMISValueType INT
DECLARE @SplitBillNumber INT
DECLARE @RoomTypeHotelNumber INT
DECLARE @FK_ReferenceNumber INT
DECLARE @IsTableBooking INT
DECLARE @MainCourceResNotInclMIS_OrderBook BIT--Main course reservation not included in MIS and order book
DECLARE @CountResToRecalc INT--No. of res. to be recalculated. 0: Standard calculation (all from defined date)
DECLARE @MISUseBookedRoomType INT--Use Booked RoomType instead of allocated RoomType
DECLARE @ThirdParam INT--for call to GetVatValueAndAccountnumbers
DECLARE @LineCounted BIT
DECLARE @tmpLineCounted BIT
DECLARE @CountryNumber INT
DECLARE @HotelCountryNumber INT
DECLARE @RestaurantReservationNumber INT
DECLARE @LFromTime DATETIME
DECLARE @LToTime DATETIME
DECLARE @LArrivalTime DATETIME
DECLARE @LDepartureTime DATETIME
DECLARE @TheArrivalTime DATETIME
DECLARE @TheDepartureTime DATETIME

--MISCalcRunning
SELECT @MISCalcRunning = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'MISCalcRunning'

SET @MISCalcRunning = ISNULL(@MISCalcRunning, 0)

IF @MISCalcRunning = 1
BEGIN
  IF @ShowPrint = 1
    PRINT 'Another MIS calculation already runs.'
  RETURN 1
END

DECLARE @MISCalcRunningFound INT

SELECT @MISCalcRunningFound = count(*) FROM HotelSetup WITH (NOLOCK) WHERE Searchkey = 'MISCalcRunning'

IF @MISCalcRunningFound = 0
  INSERT INTO HotelSetup (SearchKey, KeyValue) VALUES ( 'MISCalcRunning', 1)
ELSE
  UPDATE HotelSetup SET KeyValue = 1 WHERE Searchkey = 'MISCalcRunning'

CREATE TABLE #PacketInfo 
(
  ProductNumber INT,
  DateStamp DATE,
  PacketType INT,
  PacketNumber INT
)

CREATE TABLE #PacketWareTable --Populated by CalcPacketPriceAccExt
(
  [ResultAccountNumber] [INT] NULL,
  [DepartmentNumber] [SMALLINT] NULL,
  [PacketWarePrice] [FLOAT] NULL,
  [VatOfPacketWarePrice] [FLOAT] NULL,
  [WareGroupNumber] [FLOAT] NULL,
  [WareName] [VARCHAR](50) NULL,
  [WareType] INT NULL,
  [WareNumber] INT NULL,
  [ProductWareLinkNumber] BIGINT NULL,
  [ProductNumber] INT NULL,
  [BookedWareCount] INT NULL,
  [HotelCustomerNumber] INT NULL,
  FromTime DATETIME NULL,
  ToTime DATETIME NULL
)

CREATE TABLE #ReservationsCrossDate ([ReferenceNumber] [INT] NOT NULL)

CREATE TABLE #FoliosCrossDate ([FolioNumber] [INT] NOT NULL)

SELECT @NightAuditRunning = NightAuditRunning
FROM Terminals WITH (NOLOCK)
WHERE NightAuditRunning = 1

IF ISNULL(@NightAuditRunning, 0) = 0
  SET @NightAuditRunning = 0

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 2'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

--****************************************
--SET @NightAuditRunning = 1
--****************************************
SET @CalcMISFromDate = IsNull(@CalcMISFromDate, '')
SET @CalcMISToDate = IsNull(@CalcMISToDate, '')

--Dates
SELECT @SystemDateStr = SYSTEMDATE FROM System WITH (NOLOCK) WHERE NUMBER = 1

SET @SystemDate = CONVERT(DATETIME, @SystemDateStr)

SELECT @LastMISUpdate = CONVERT(DATETIME, Keyvalue) FROM HotelSetup WITH (NOLOCK) WHERE Searchkey = 'LastMISUpdate'

SELECT @LastMISChangedUpdate = CONVERT(DATETIME, Keyvalue, 126) --yyyy-mm-ddThh:mi:ss.mmm (no spaces)
FROM HotelSetup WITH (NOLOCK)
WHERE Searchkey = 'LastMISChangedUpdate'

--** Recalc ActualWareCount in first nightAudit after update *************************************
IF @NightAuditRunning = 1
BEGIN
  DECLARE @TempMISWareCount CHAR = '0'
  SELECT @TempMISWareCount = KeyValue FROM HotelSetup(NOLOCK) WHERE SearchKey = 'TempMISWareCount'
  SET @TempMISWareCount = IsNull(@TempMISWareCount, '0')

  IF @ShowPrint = 1
    PRINT '@TempMISWareCount=' + @TempMISWareCount

  IF @TempMISWareCount = '0'
  BEGIN
    SET @CalcOnlyChangedReservations = 0 --Force full calc forward

    DECLARE @CurrentYear INT = DatePart(year, @SystemDate)
    --1. jan. forrige år
    DECLARE @FirstDayPrevYear DATETIME = DateFromParts(@CurrentYear - 1, 1, 1)

    SET @CalcMISFromDate = Convert(CHAR(8), @FirstDayPrevYear, 112)

    UPDATE HotelSetup SET KeyValue = '1' WHERE SearchKey = 'TempMISWareCount'

    IF @@ROWCOUNT = 0
      INSERT INTO HotelSetup (SearchKey, KeyValue) VALUES ('TempMISWareCount', '1')
  END
END

--Log
DECLARE @DatesForLog VARCHAR(8)
SET @DatesForLog = ''

IF @CalcMISFromDate = ''
  SET @DatesForLog = 'NORMAL'
ELSE
BEGIN
  SET @DatesForLog = SUBSTRING(@CalcMISFromDate, 5, 4)

  IF @CalcMISToDate <> ''
    SET @DatesForLog += SUBSTRING(@CalcMISToDate, 5, 4)
END

INSERT INTO MISTotals (SystemDate, DateStamp, ReferenceNumber)
VALUES (GetDate(), @DatesForLog, - 99)

-- For discount calculation
SELECT @OrderBookBudgetCalcDiscount = CONVERT(BIT, KeyValue) FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'OrderBookBudgetCalcDiscount'
SET @OrderBookBudgetCalcDiscount = ISNULL(@OrderBookBudgetCalcDiscount, 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'
SET @ChargeDiscountAsProduct = ISNULL(@ChargeDiscountAsProduct, 1)

SELECT @DiscountWareNumber = DiscountWareNumber, 
  @DiscountResultAccountNumber = DiscountResultAccountNumber, 
  @DiscountVatValueWare = DiscountVatValueWare,
  @DiscountMISValueType = DiscountMISValueType
FROM dbo.GetDiscountWareInfo()
-- For discount calculation end

SELECT @IncludeDayroomsInSoldRooms = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'IncludeDayroomsInSoldRooms'

SELECT @DayroomsLaterThanTime = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'DayroomsLaterThanTime'

IF ISNULL(@IncludeDayroomsInSoldRooms, 0) = 0
  SET @IncludeDayroomsInSoldRooms = 0

IF ( (@DayroomsLaterThanTime = '')  OR (@DayroomsLaterThanTime IS NULL))
  SET @DayroomsLaterThanTime = '13:00'

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

Declare @CalcPriceBasedOnOnePersonPaysForAll bit
SELECT @CalcPriceBasedOnOnePersonPaysForAll=KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey ='CalcPriceBasedOnOnePersonPaysForAll'
SET @CalcPriceBasedOnOnePersonPaysForAll=IsNull(@CalcPriceBasedOnOnePersonPaysForAll, 0)

IF @CalcPriceBasedOnOnePersonPaysForAll = 0
  SET @OnePersonPaysForAll = -1

SELECT @NameListSettingHotelSetup = CONVERT(INTEGER, KeyValue) FROM Hotelsetup WITH (NOLOCK) WHERE Searchkey = 'NameListReservationPerPerson';
SET @NameListSettingHotelSetup = ISNULL(@NameListSettingHotelSetup, 0);

SELECT @IncludeTentative = CONVERT(BIT, KeyValue) FROM Hotelsetup WITH (NOLOCK) WHERE Searchkey = 'IncludeTentativeInMISAndOrderbook';
IF ISNULL(@IncludeTentative, 0) = 0
  SET @IncludeTentative = 0

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

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

SELECT @MISUseBookedRoomType = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'MISUseBookedRoomType'
SET @MISUseBookedRoomType = ISNULL(@MISUseBookedRoomType, 1)--Default 1

SELECT @MISAllotmentEnable = CONVERT(BIT, IsNull(KeyValue, '0')) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'MISAllotmentEnable'

SET @FirstFetch = 1
SET @TableCount = 0-- 0 = Roomline og 1=Confline, 2=NoRoom, no Confline   
  -- Check if StartDate or EndDate before Systemdate -> change!   

SELECT @OldSegmentNumber = Number FROM SEGMENTS WITH (NOLOCK) WHERE TEXT = 'Old system'

IF ISNULL(@OldSegmentNumber, 0) = 0
  SET @OldSegmentNumber = 0

--Find AddOn Ware
--Declare @AddonBalanceAccountNumber int
DECLARE @AddonResultAccountNumber INT
DECLARE @AddonWareText VARCHAR(100)
DECLARE @AddonWareType INT
DECLARE @AddonWareNumber INT

SELECT @AddonResultAccountNumber = Ware.ResultAccountNumber, @AddonWareText = Ware.WareName, @AddonWaretype = Ware.Type, @AddonWareNumber = Ware.WareNumber
FROM WARE WITH (NOLOCK)
INNER JOIN WAREGROUPS WITH (NOLOCK) ON WARE.WareGroupNumber = WAREGROUPS.WareGroupNumber
WHERE WAREGROUPS.Payment = 4
AND Ware.MarkAsDeleted IS NULL
AND Ware.SortNumber = 5

DECLARE @LastMISChangedUpdateFound INT

SELECT @LastMISChangedUpdateFound = COUNT(*) FROM HotelSetup WITH (NOLOCK) WHERE Searchkey = 'LastMISChangedUpdate'

IF @LastMISChangedUpdateFound = 0
BEGIN
  SET @LastMISChangedUpdate = @LastMISUpdate

  INSERT INTO HotelSetup (SearchKey, KeyValue)
  VALUES ('LastMISChangedUpdate', CONVERT(CHAR(23), @LastMISUpdate, 126))
END

-- Limit the recalculation date 
EXEC dbo.GetLatestDeletedBefore @LatestDeletedBefore OUTPUT

IF @CalcMISFromDate <> '' AND @CalcMISFromDate < @LatestDeletedBefore 
  SET @CalcMISFromDate = @LatestDeletedBefore
SET @CalcSystemDateOnly = ISNULL(@CalcSystemDateOnly, 0)

IF @CalcMISFromDate = '' -- Normal update from Marketing or NightAudit
BEGIN
  DECLARE @StartD DATETIME

  IF @NightAuditRunning = 1
    SET @StartD = ISNULL(CONVERT(DATETIME, @LastMISUpdate) - 1, @SystemDate)
  ELSE
    SET @StartD = ISNULL(CONVERT(DATETIME, @LastMISUpdate) - 1, @SystemDate - 1)

  SET @CalcMISToDate = '21001231'
  SET @FormatedStartDate = CONVERT(CHAR(8), @StartD, 112)
END
ELSE
BEGIN
  SET @FormatedStartDate = @CalcMISFromDate

  IF ISNULL(@CalcMISToDate, '') = '' --default
    SET @CalcMISToDate = '21001231'
END

IF @CalcSystemDateOnly = 1
BEGIN
  SET @FormatedStartDate = @SystemDateStr
  SET @CalcMISToDate = @SystemDateStr
END

IF @ShowPrint = 1
  PRINT '@FormatedStartDate = ' + @FormatedStartDate + ' @CalcMISToDate = ' + @CalcMISToDate

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 3'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

--Genberegning af rettede reservationer
CREATE TABLE #ResToRecalc (ReferenceNumber INT)

IF @DebugReferenceNumber <> - 1
  INSERT INTO #ResToRecalc (ReferenceNumber) VALUES (@DebugReferenceNumber)

IF @CalcOnlyChangedReservations = 1 AND ISNULL(@DebugReferenceNumber, 0) <= 0
BEGIN
  INSERT INTO #ResToRecalc (ReferenceNumber)
  SELECT FK_ReferenceNumber
  FROM ReservationsExt WITH (NOLOCK)
  WHERE ReservationsExt.LastUpdDateStamp >= @LastMISChangedUpdate
  
  UNION
  
  SELECT ReferenceNumber
  FROM ReservationRoomLine WITH (NOLOCK)
  INNER JOIN ReservationRoomLineXTab ON ReservationRoomLineXTab.LineNumber = ReservationRoomLine.LineNumber
  WHERE ReservationRoomLine.LastUpdDateStamp >= @LastMISChangedUpdate
  
  UNION
  
  SELECT ReferenceNumber
  FROM ReservationConferenceLine WITH (NOLOCK)
  WHERE ReservationConferenceLine.LastUpdDateStamp >= @LastMISChangedUpdate
  
  UNION
  
  SELECT ReferenceNumber
  FROM ArrangementLines WITH (NOLOCK)
  INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementReservationsXtab.ArrangementLineNumber = ArrangementLines.ArrangementLineNumber
  WHERE ArrangementLines.LastUpdDateStamp >= @LastMISChangedUpdate
END

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 4'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

SELECT @CountResToRecalc = COUNT(*)
FROM #ResToRecalc

IF @CountResToRecalc = 0 AND @CalcOnlyChangedReservations = 1
BEGIN
  INSERT INTO #ResToRecalc (ReferenceNumber)
  VALUES (- 2)--Dummy to avoid "WHERE ... IN ()"

  SET @CountResToRecalc = 1--To avoid standard calculation
END

IF @ShowPrint = 1
  PRINT 'Genberegning af rettede reservationer, @CountResToRecalc=' + CONVERT(CHAR(6), @CountResToRecalc) + ' @LastMISChangedUpdate=' + CONVERT(VARCHAR, @LastMISChangedUpdate) + ' @FormatedStartDate=' + CONVERT(VARCHAR, @FormatedStartDate)

--SELECT '#ResToRecalc', ReferenceNumber from #ResToRecalc order by ReferenceNumber
--Logs @CountResToRecalc
INSERT INTO MISTotals (SystemDate, DateStamp, ReferenceNumber)
VALUES (GETDATE(), 'RECALC', @CountResToRecalc)

--Genberegning af rettede reservationer
-- Get reference numbers crossing the @FormatedStartDate Reservations are deleted and recalculated as whole reservations. From arrivaldate to departure date always.
IF ISNULL(@DebugReferenceNumber, 0) > 0
  INSERT INTO #ReservationsCrossDate VALUES (@DebugReferenceNumber)
ELSE
BEGIN
  IF @CalcSystemDateOnly = 0
  BEGIN
    INSERT INTO #ReservationsCrossDate
    SELECT DISTINCT ReferenceNumber
    FROM Reservations WITH (NOLOCK)
    WHERE (
        (
          ArrivalDate <= @FormatedStartDate
          AND DepartureDate >= @FormatedStartDate
          )
        OR (
          ArrivalDate <= @CalcMISToDate
          AND DepartureDate >= @CalcMISToDate
          )
        )
      AND ReferenceNumber IS NOT NULL
  
    UNION ALL
  
    SELECT DISTINCT ReferenceNumber
    FROM RESERVATIONCONFERENCELINE WITH (NOLOCK)
    WHERE (
        (
          ArrivalDate <= @FormatedStartDate
          AND DepartureDate >= @FormatedStartDate
          )
        OR (
          ArrivalDate <= @CalcMISToDate
          AND DepartureDate >= @CalcMISToDate
          )
        )
      AND ReferenceNumber IS NOT NULL
  END
END

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 5'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

-- Get Folio numbers crossing the @FormatedStartDate Folios are deleted and recalculated as whole Folios.
INSERT INTO #FoliosCrossDate
SELECT DISTINCT 
CASE WHEN FolioNumber = - 1  THEN 
    - 99 --From SMS-import, not to be mixed with -1 meening "no folio" = from reservation
  ELSE 
    FolioNumber
END AS FolioNumber
FROM Transactions WITH (NOLOCK)
WHERE (CONVERT(CHAR(8), DateStamp, 112) >= @FormatedStartDate)

DECLARE @CancelDeleteDate CHAR(8)

IF @NightAuditRunning = 1
  SET @CancelDeleteDate = CONVERT(CHAR(8), DATEADD(DAY, - 1, CONVERT(DATE, @FormatedStartDate)), 112)
ELSE
  SET @CancelDeleteDate = @FormatedStartDate

DELETE
FROM MISTable
WHERE ReadOnly = 0
  AND ReservationStatus NOT IN (7, 8)
  AND (
    (
      @CalcSystemDateOnly = 0
      AND @CountResToRecalc = 0
      AND DateStamp >= @FormatedStartDate
      AND DateStamp < @CalcMISToDate
      )
    OR (
      @CalcSystemDateOnly = 0
      AND (
        MISTable.ReferenceNumber IN (SELECT * FROM #ReservationsCrossDate)
        AND MisTable.FolioNumber = - 1
        )
      )
    OR (MISTable.FolioNumber IN (SELECT * FROM #FoliosCrossDate))
    OR (referencenumber IN (SELECT * FROM #ResToRecalc)
      AND MisTable.FolioNumber = - 1
      AND DateStamp >= @FormatedStartDate
      )
    )

--Not deleted on current date
DELETE
FROM MISTable
WHERE ReadOnly = 0
  AND ReservationStatus IN (7, 8)
  AND (
    (
      @CalcSystemDateOnly = 0
      AND @CountResToRecalc = 0
      AND DateStamp > @CancelDeleteDate
      AND DateStamp < @CalcMISToDate
      )
    OR (
      @CalcSystemDateOnly = 0
      AND (
        MISTable.ReferenceNumber IN (SELECT * FROM #ReservationsCrossDate)
        AND MisTable.FolioNumber = - 1
        )
      )
    OR (MISTable.FolioNumber IN (SELECT * FROM #FoliosCrossDate))
    OR (
      referencenumber IN (SELECT * FROM #ResToRecalc)
      AND MisTable.FolioNumber = - 1
      AND DateStamp > @CancelDeleteDate
      )
    )

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 6'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

--FolioNumber = -1 are records from reservations 
SELECT @Arr24 = KeyValue FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'Arr24HoursStarts'

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

SELECT @AddonAsWare = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'AddonAsWare'
SET @AddonAsWare = IsNull(@AddonAsWare, 0)

SELECT @ChargeAddonAsProduct = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'ChargeAddonAsProduct'
SET @ChargeAddonAsProduct = IsNull(@ChargeAddonAsProduct, 0)

SELECT @DefaultMISPointOfSale = CONVERT(INT, KeyValue) FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'DefaultMISPos'
SET @DefaultMISPointOfSale = ISNULL(@DefaultMISPointOfSale, - 1)

SELECT @DefaultMISSegment = CONVERT(INT, KeyValue) FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'DefaultMISSegment'
SET @DefaultMISSegment = ISNULL(@DefaultMISSegment, - 1)

SELECT @DefaultMISGuestType = CONVERT(INT, KeyValue) FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'DefaultMISGuestType'
SET @DefaultMISGuestType = ISNULL(@DefaultMISGuestType, - 1)

SELECT @DefaultMISPurposeCode = CONVERT(INT, KeyValue) FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'DefaultMISPurposeCode'
SET @DefaultMISPurposeCode = ISNULL(@DefaultMISPurposeCode, - 1)

SELECT @HotelCountryNumber = CONVERT(INT, KeyValue) FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'CountryCode'
IF @@ROWCOUNT = 0
  SELECT TOP 1 @HotelCountryNumber = CountryNumber FROM Countries WITH (NOLOCK)

SELECT @ProductWareLinkNumberMis = MAX(ProductWareLinkNumber) + 1 FROM MisTable WITH (NOLOCK)
SELECT @ProductWareLinkNumberTrans = MAX(ProductWareLinkNumber) + 1 FROM Transactions WITH (NOLOCK)

SET @ProductWareLinkNumberMis = ISNULL(@ProductWareLinkNumberMis, 0)
SET @ProductWareLinkNumberTrans = ISNULL(@ProductWareLinkNumberTrans, 0)
SET @ProductWareLinkNumber = @ProductWareLinkNumberTrans

IF @ProductWareLinkNumberMis > @ProductWareLinkNumberTrans
  SET @ProductWareLinkNumber = @ProductWareLinkNumberMis + 1000000 -- 100000 -> 1000000 
-- Be sure not to conflict when calculating mis on systemdate only. We need a range of pwln's for posted transactions on day.
--In order not to conflict with future values from Transaction, as we don't recalculate every res. every time

IF @ProductWareLinkNumber < 500000
  SET @ProductWareLinkNumber = 500000

IF @ShowPrint = 1
BEGIN
  PRINT '@ProductWareLinkNumber=' + CONVERT(VARCHAR, @ProductWareLinkNumber) + ', @ProductWareLinkNumberMis=' + CONVERT(VARCHAR, @ProductWareLinkNumberMis) + ', @ProductWareLinkNumberTrans=' + CONVERT(VARCHAR, @ProductWareLinkNumberTrans)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

SET @ProductWareLinkNumber = ISNULL(@ProductWareLinkNumber, 1)

CREATE TABLE #ReferenceExtrasTable 
(
  ReferenceNumber INT NOT NULL,
  CurrentDate CHAR(8)
)

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 7'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

IF @CalcSystemDateOnly = 0
BEGIN
  WHILE (@TableCount <= 2) --Include res. without room or hall (@DayProduct))
  BEGIN
    SET @TableCount = @TableCount + 1

    IF @TableCount = 1 -- Roomline   
    BEGIN
      SET @ValueType = 1
      SET @PrevLineNumber = 0
      SET @GenerateDayProduct = 0
      SET @PrevGuestNumber = 0
      SET @LineCounted = 0

      DECLARE ReservationCur CURSOR FAST_FORWARD READ_ONLY FOR --No namelist
        SELECT DISTINCT
          CAST(0 AS TINYINT) AS Room_HallType, ReservationRoomLine.LineNumber,
          CASE WHEN @MISUseBookedRoomType = 1 THEN 
            ISNULL(ReservationRoomLine.BookedTypeNumber, Rooms.Roomtypenumber)
          ELSE 
            ISNULL (Rooms.Roomtypenumber, ReservationRoomLine.BookedTypeNumber)
          END, 
          ReservationRoomLine.RoomNumber, ReservationRoomLineXTab.ReferenceNumber, ReservationRoomLineXTab.GuestNumber, ISNULL(ReservationRoomLine.StatusRL, ISNULL(Reservations.Status, 0)), 
          Reservations.MarketSegment, Reservations.PointOfSale, Reservations.GuestType, Reservations.PurposeCode, ReservationRoomLine.ArrivalDate, ReservationRoomLine.DepartureDate, ReservationRoomLine.DepartureTime, 
          ReservationRoomLine.Adults, ReservationRoomLine.Children1, ReservationRoomLine.Children2, ReservationRoomLine.Adults, ReservationRoomLine.Children1, ReservationRoomLine.Children2, 
          ReservationRoomLine.ProductNumber, ReservationRoomLine.NumberOfRooms, ReservationRoomLine.PriceOverwritten, ReservationRoomLine.Price, ReservationRoomLine.FirstPrice1, 
          ReservationRoomLine.PriceOverwritten2, ReservationRoomLine.FirstPrice2, ReservationRoomLine.Day2, ReservationRoomLine.ProductNumber2, 
          ReservationRoomLine.PriceOverwritten3, ReservationRoomLine.FirstPrice3, ReservationRoomLine.Day3, ReservationRoomLine.ProductNumber3, 
          ReservationRoomLine.PriceOverwritten4, ReservationRoomLine.FirstPrice4, ReservationRoomLine.Day4, ReservationRoomLine.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) , ISNULL(ReservationRoomLine.NameListSetting, 0), 1, ISNULL(Reservations.FK_CampaignCode, - 1), ISNULL(ReservationMain.FK_ProjectCode, - 1), ISNULL(ReservationMain.StaffID, - 1), 
          CASE WHEN ((Rooms.CustomerNumber IS NOT NULL AND ReservationAddress.Link IS NOT NULL) AND Rooms.CustomerNumber = ReservationAddress.Link) THEN 1 ELSE 0 END, 
          Reservations.SplitBill, RoomTypes.HotelNumber, FK_ReferenceNumber, ReservationRoomLine.PlusProductSamePeriod,
          ISNULL(CASE WHEN ReservationAddress.CountryNumber IS NULL THEN
            (SELECT TOP 1 CountryNumber FROM Countries WITH (NOLOCK) WHERE Countries.CountryCode = ReservationAddress.CountryCode)
          ELSE
            ReservationAddress.CountryNumber
          END, @HotelCountryNumber),
          ISNULL
          (
            (
              SELECT TOP 1 d.PK_Department
              FROM Departments d
              WHERE d.HotelNumber = ISNULL(RoomTypes.HotelNumber, 0)
              AND ISNULL(d.MarkAsDeleted, 0) = 0 
              AND d.AutoCharge = 1
            ),
            (
              ISNULL
              (
                (
                  SELECT TOP 1 d.PK_Department
                  FROM Departments d
                  WHERE d.HotelNumber = ISNULL(RoomTypes.HotelNumber, 0)
                  AND ISNULL(d.MarkAsDeleted, 0) = 0
                ),
                (
                  SELECT TOP 1 d.PK_Department
                  FROM Departments d
                  WHERE d.HotelNumber = ISNULL(RoomTypes.HotelNumber, 0)
                )
              )
            )
          ),
          CONVERT(DATETIME, ReservationRoomLine.ArrivalTime, 108), CONVERT(DATETIME, ReservationRoomLine.DepartureTime, 108)
        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 <> ReservationRoomLine.ArrivalDate) OR (ReservationRoomLine.DepartureDate = ReservationRoomLine.ArrivalDate AND @IncludeDayroomsInSoldRooms = 1))
        INNER JOIN Reservations WITH (NOLOCK) ON ReservationRoomLineXTab.ReferenceNumber = Reservations.ReferenceNumber
          AND ReservationRoomLineXTab.GuestNumber = Reservations.GuestNumber
          AND ((@IncludeTentative = 0 AND ISNULL(ReservationRoomLine.StatusRL, ISNULL(Reservations.Status, 0)) IN (0, 1, 2, 5, 6, 7, 8)) OR (@IncludeTentative = 1 AND ISNULL(ReservationRoomLine.StatusRL, ISNULL(Reservations.Status, 0)) IN (0, 1, 2, 4, 5, 6, 7, 8)))
        LEFT OUTER JOIN ReservationConferenceLine WITH (NOLOCK) ON Reservations.ReferenceNumber = ReservationConferenceLine.ReferenceNumber
        INNER JOIN ReservationMain WITH (NOLOCK) ON ReservationMain.ReferenceNumber = Reservations.ReferenceNumber
        LEFT OUTER JOIN Rooms WITH (NOLOCK) ON ReservationRoomLine.RoomNumber = Rooms.RoomNumber
        LEFT OUTER JOIN RoomTypes WITH (NOLOCK) ON ReservationRoomLine.BookedTypeNumber = RoomTypes.RoomTypeNumber
        LEFT OUTER JOIN Customer WITH (NOLOCK) ON ISNULL(RoomTypes.HotelNumber, 0) = Customer.HotelNumber
          AND Customer.HotelNumber >= 0
          AND Customer.CustomerTypeNumber = 7
          AND ISNULL(Customer.MarkAsDeleted, 0) = 0
        LEFT JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.ReferenceNumber = Reservations.ReferenceNumber
          AND ReservationAddressXTab.GuestNumber = Reservations.GuestNumber
          AND ReservationAddressXTab.AddressTypeNumber = 1
        LEFT JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = ReservationAddressXTab.AddressNumber
          AND ReservationAddress.AddressType = 1
        LEFT OUTER JOIN ReservationReservationXtab resX WITH (NOLOCK) ON resx.FK_ReferenceNumber = Reservations.ReferenceNumber
        LEFT OUTER JOIN Reservations sub WITH (NOLOCK) ON sub.ReferenceNumber = resx.FK_ReferenceNumberSub
          AND sub.STATUS < 7
        WHERE ((@CountResToRecalc = 0 AND ReservationRoomLine.DepartureDate >= @FormatedStartDate AND ReservationRoomLine.DepartureDate <= @CalcMISToDate) OR 
          ReservationRoomLineXTab.ReferenceNumber IN (SELECT * FROM #ReservationsCrossDate WITH (NOLOCK)) OR 
          (ReservationRoomLineXTab.ReferenceNumber IN (SELECT * FROM #ResToRecalc) AND ReservationRoomLine.DepartureDate >= @FormatedStartDate))
        AND NOT (ISNULL(Reservations.RequestorID, 0) = - 2  AND ISNULL(ReservationMain.CreationInProgress, 0) = 1 AND Reservations.Status = 7) --RequestorID = -2 => Online, CreationInProgress = 1 => canceled by service
      
        UNION ALL
      
        --Namelist
        SELECT DISTINCT
          CAST(0 AS TINYINT), ReservationRoomLine.LineNumber, 
          CASE WHEN @MISUseBookedRoomType = 1 THEN 
            ISNULL(ReservationRoomLine.BookedTypeNumber, Rooms.Roomtypenumber)
          ELSE 
            ISNULL(Rooms.Roomtypenumber, ReservationRoomLine.BookedTypeNumber)
          END, 
          ReservationRoomLine.RoomNumber, Reservations.ReferenceNumber, Reservations.GuestNumber, ISNULL(Reservations.Status, 0), Reservations.MarketSegment, Reservations.PointOfSale, Reservations.GuestType, Reservations.PurposeCode,
          Reservations.ArrivalDate AS ArrivalDate, Reservations.DepartureDate AS DepartureDate, Reservations.DepartureTime, 
          Reservations.Adults, Reservations.Children1, Reservations.Children2, Reservations.PaysAdults, Reservations.PaysChildren1, Reservations.PaysChildren2, Reservations.ProductNumber, ReservationRoomLine.NumberOfRooms, 
          Reservations.PriceOverwritten, Reservations.Price, Reservations.FirstPrice1, Reservations.PriceOverwritten2, Reservations.FirstPrice2, Reservations.Day2, Reservations.ProductNumber2, 
          Reservations.PriceOverwritten3, Reservations.FirstPrice3, Reservations.Day3, Reservations.ProductNumber3, 
          Reservations.PriceOverwritten4, Reservations.FirstPrice4, Reservations.Day4, Reservations.ProductNumber4, 0, 
          CASE WHEN ReservationConferenceLine.ReservationConfLineNumber > 0 THEN 1 ELSE 0 END, 
          ISNULL(Customer.CustomerNumber, - 1), ISNULL(ReservationRoomLine.NameListSetting, 0), 1, -- Plenum
          isnull(Reservations.FK_CampaignCode, - 1), ISNULL(ReservationMain.FK_ProjectCode, - 1), ISNULL(ReservationMain.StaffID, - 1), 
          CASE WHEN ((Rooms.CustomerNumber IS NOT NULL AND ReservationAddress.Link IS NOT NULL) AND Rooms.CustomerNumber = ReservationAddress.Link) THEN 1 ELSE 0 END, 
          Reservations.SplitBill, RoomTypes.HotelNumber, FK_ReferenceNumber, Reservations.PlusProductSamePeriod,
          ISNULL(CASE WHEN ReservationAddress.CountryNumber IS NULL THEN
            (SELECT TOP 1 CountryNumber FROM Countries WITH (NOLOCK) WHERE Countries.CountryCode = ReservationAddress.CountryCode)
          ELSE
            ReservationAddress.CountryNumber
          END, @HotelCountryNumber),
          ISNULL
          (
            (
              SELECT TOP 1 d.PK_Department
              FROM Departments d
              WHERE d.HotelNumber = ISNULL(RoomTypes.HotelNumber, 0)
              AND ISNULL(d.MarkAsDeleted, 0) = 0 
              AND d.AutoCharge = 1
            ),
            (
              ISNULL
              (
                (
                  SELECT TOP 1 d.PK_Department
                  FROM Departments d
                  WHERE d.HotelNumber = ISNULL(RoomTypes.HotelNumber, 0)
                  AND ISNULL(d.MarkAsDeleted, 0) = 0
                ),
                (
                  SELECT TOP 1 d.PK_Department
                  FROM Departments d
                  WHERE d.HotelNumber = ISNULL(RoomTypes.HotelNumber, 0)
                )
              )
            )
          ),
          CONVERT(DATETIME, Reservations.ArrivalTime, 108), CONVERT(DATETIME, Reservations.DepartureTime, 108)
          FROM ReservationRoomLine WITH (NOLOCK)
          INNER JOIN ReservationRoomLineXTab WITH (NOLOCK) ON ReservationRoomLine.LineNumber = ReservationRoomLineXTab.LineNumber
            AND ReservationRoomLineXTab.Referencenumber > 0
            AND ReservationRoomLineXTab.GuestNumber > 0
          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, 7, 8)) OR (@IncludeTentative = 1 AND Reservations.Status IN (0, 1, 2, 4, 5, 6, 7, 8)))
          AND Reservations.GuestNumber > 0
          AND ((Reservations.Adults + Reservations.Children1 + Reservations.Children2 > 0)  OR ((Reservations.PaysAdults + Reservations.PaysChildren1 + Reservations.PaysChildren2) > 0))
          AND ((Reservations.DepartureDate <> Reservations.ArrivalDate) OR (Reservations.DepartureDate = Reservations.ArrivalDate AND @IncludeDayroomsInSoldRooms = 1))
        LEFT OUTER JOIN ReservationConferenceLine WITH (NOLOCK) ON Reservations.ReferenceNumber = ReservationConferenceLine.ReferenceNumber
        INNER JOIN ReservationMain WITH (NOLOCK) ON ReservationMain.ReferenceNumber = Reservations.ReferenceNumber
        LEFT OUTER JOIN Rooms WITH (NOLOCK) ON ReservationRoomLine.RoomNumber = Rooms.RoomNumber
        LEFT OUTER JOIN RoomTypes WITH (NOLOCK) ON ReservationRoomLine.BookedTypeNumber = RoomTypes.RoomTypeNumber
        LEFT OUTER JOIN Customer WITH (NOLOCK) ON ISNULL(RoomTypes.HotelNumber, 0) = Customer.HotelNumber
          AND Customer.HotelNumber >= 0
          AND Customer.CustomerTypeNumber = 7
          AND ISNULL(Customer.MarkAsDeleted, 0) = 0
        LEFT JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.ReferenceNumber = Reservations.ReferenceNumber
          AND ReservationAddressXTab.GuestNumber = Reservations.GuestNumber
          AND ReservationAddressXTab.AddressTypeNumber = 1
        LEFT JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = ReservationAddressXTab.AddressNumber
          AND ReservationAddress.AddressType = 1
        LEFT OUTER JOIN ReservationReservationXtab resX WITH (NOLOCK) ON resx.FK_ReferenceNumber = Reservations.ReferenceNumber
        LEFT OUTER JOIN Reservations sub WITH (NOLOCK) ON sub.ReferenceNumber = resx.FK_ReferenceNumberSub
          AND sub.Status < 7
        WHERE ((@CountResToRecalc = 0 AND ReservationRoomLine.DepartureDate >= @FormatedStartDate AND ReservationRoomLine.DepartureDate <= @CalcMISToDate) OR 
          ReservationRoomLineXTab.ReferenceNumber IN (SELECT * FROM #ReservationsCrossDate WITH (NOLOCK)) OR 
          (ReservationRoomLineXTab.ReferenceNumber IN (SELECT * FROM #ResToRecalc) AND ReservationRoomLine.DepartureDate >= @FormatedStartDate))
        AND NOT (ISNULL(Reservations.RequestorID, 0) = - 2 AND ISNULL(ReservationMain.CreationInProgress, 0) = 1 AND Reservations.Status = 7)
        ORDER BY ReferenceNumber, ReservationRoomLine.linenumber, ArrivalDate, DepartureDate DESC, GuestNumber
      OPEN ReservationCur

      FETCH NEXT FROM ReservationCur INTO @Room_HallType, @LINENUMBER, @BookedTypeNumber, @RoomNumber, @ReferenceNumber, @GuestNumber, @Status, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @ArrivalDate, @DepartureDate, @DepartureTime,
        @Adults, @Children1, @Children2, @PaysAdults, @PaysChildren1, @PaysChildren2, @ProductNumber, @NumberOfRooms, 
        @PriceOverwritten, @Price, @FirstPrice1, @PriceOverwritten2, @FirstPrice2, @Day2, @ProductNumber2, @PriceOverwritten3, @FirstPrice3, @Day3, @ProductNumber3, @PriceOverwritten4, @FirstPrice4, @Day4, @ProductNumber4, 
        @ConferenceLineOnRes, @ConflineOnMainRes, @HotelCustomerNumber, @NameListSetting, @Plenum, @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber, @RoomTypeHotelNumber, @FK_ReferenceNumber, @PlusProductSamePeriod, @CountryNumber, @DepartmentNumber,
        @LArrivalTime, @LDepartureTime
    END -- RoomLine

    IF @TableCount = 2 -- Confline   
    BEGIN
      SET @ConferenceLineOnRes = 1
      SET @GenerateDayProduct = 1

      DECLARE ReservationCur CURSOR FAST_FORWARD READ_ONLY FOR
        SELECT DISTINCT CAST(1 AS TINYINT) AS Room_HallType, ReservationConferenceLine.BookedConferenceRoomTypeNumber, ReservationConferenceLine.ReservationConfLineNumber, ReservationConferenceLine.ConferenceRoomNumber, 
          ReservationConferenceLine.ArrivalDate, ReservationConferenceLine.DepartureDate, ReservationConferenceLine.ProductNumber, ReservationConferenceLine.NumberOfRooms, ISNULL(Reservations.Status, 0), Reservations.MarketSegment,
          Reservations.PointOfSale, Reservations.GuestType, Reservations.PurposeCode, ReservationConferenceLINE.PriceOverWritten, ReservationConferenceLine.Adults, ReservationConferenceLine.Children1, ReservationConferenceLine.Children2, ReservationConferenceLine.Price, 
          ReservationConferenceLine.ReferenceNumber, ReservationConferenceLine.PackageNumber, ReservationConferenceLine.ArrivalTime, ReservationConferenceLine.DepartureTime, ISNULL(ISNULL(CustomerHS.CustomerNumber, Customer.CustomerNumber), -1),
          ISNULL(ReservationConferenceLine.Plenum, 0), ISNULL(Reservations.FK_CampaignCode, - 1), ISNULL(ReservationMain.FK_ProjectCode, - 1), ISNULL(ReservationMain.StaffID, - 1), 0, Reservations.SplitBill, 0, FK_ReferenceNumber, ReservationConferenceLine.TableBooking,
          ISNULL(CASE WHEN ReservationAddress.CountryNumber IS NULL THEN
            (SELECT TOP 1 CountryNumber FROM Countries WITH (NOLOCK) WHERE Countries.CountryCode = ReservationAddress.CountryCode)
          ELSE
            ReservationAddress.CountryNumber
          END, @HotelCountryNumber),
          ISNULL(ReservationConferenceLine.FK_ChargeDepartment,
          (
            ISNULL
            (
              (
                SELECT TOP 1 d.PK_Department
                FROM Departments d
                WHERE d.HotelNumber = ISNULL(CustomerHS.HotelNumber, 0)
                AND ISNULL(d.MarkAsDeleted, 0) = 0 
                AND d.AutoCharge = 1        
              ),
              (
                ISNULL
                (
                  (
                    SELECT TOP 1 d.PK_Department
                    FROM Departments d
                    WHERE d.HotelNumber = ISNULL(CustomerHS.HotelNumber, 0)
                    AND ISNULL(d.MarkAsDeleted, 0) = 0
                  ),
                  (
                    SELECT TOP 1 d.PK_Department
                    FROM Departments d
                    WHERE d.HotelNumber = ISNULL(CustomerHS.HotelNumber, 0)
                  )
                )
              )
            )
          )),
          CONVERT(DATETIME, ReservationConferenceLine.ArrivalTime, 108), CONVERT(DATETIME, ReservationConferenceLine.DepartureTime, 108)
        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, 7, 8)) OR (@IncludeTentative = 1 AND Reservations.Status IN (0, 1, 2, 4, 5, 6, 7, 8)))
          AND Reservations.ReferenceNumber > 0
          AND Reservations.GuestNumber = ISNULL(ReservationConferenceLine.GuestNo, 0)
        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 ISNULL(Customer.MarkAsDeleted, 0) = 0
        LEFT OUTER JOIN ConferenceRooms WITH (NOLOCK) ON ReservationConferenceLine.ConferenceRoomNumber = ConferenceRooms.ConferenceRoomNumber
        LEFT OUTER JOIN ConferenceRoomTypes WITH (NOLOCK) ON ConferenceRoomTypes.ConferenceRoomTypeNumber = ReservationConferenceLine.BookedConferenceRoomTypeNumber
        LEFT OUTER JOIN Customer CustomerHS WITH (NOLOCK) ON CustomerHS.HotelNumber = ISNULL(ISNULL(ConferenceRoomTypes.HotelNumber, ConferenceRooms.HotelNumber), 0)
          AND CustomerHS.HotelNumber >= 0
          AND CustomerHS.CustomerTypeNumber = 7
          AND ISNULL(CustomerHS.MarkAsDeleted, 0) = 0
        LEFT OUTER JOIN ReservationReservationXtab resX WITH (NOLOCK) ON resx.FK_ReferenceNumber = Reservations.ReferenceNumber
        LEFT OUTER JOIN Reservations sub WITH (NOLOCK) ON sub.ReferenceNumber = resx.FK_ReferenceNumberSub
          AND sub.Status < 7
        LEFT JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.ReferenceNumber = Reservations.ReferenceNumber
          AND ReservationAddressXTab.GuestNumber = Reservations.GuestNumber
          AND ReservationAddressXTab.AddressTypeNumber = 1
        LEFT JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = ReservationAddressXTab.AddressNumber
          AND ReservationAddress.AddressType = 1
        WHERE ((@CountResToRecalc = 0 AND Reservations.DepartureDate >= @FormatedStartDate AND Reservations.DepartureDate <= @CalcMISToDate) OR 
          Reservations.ReferenceNumber IN (SELECT * FROM #ReservationsCrossDate WITH (NOLOCK)) OR 
          (Reservations.ReferenceNumber IN (SELECT * FROM #ResToRecalc) AND Reservations.DepartureDate >= @FormatedStartDate))
        AND NOT (ISNULL(Reservations.RequestorID, 0) = - 2 AND ISNULL(ReservationMain.CreationInProgress, 0) = 1 AND Reservations.Status = 7)
        ORDER BY ReservationConferenceLine.ReferenceNumber, ReservationConferenceLine.ReservationConfLineNumber
      OPEN ReservationCur

      FETCH NEXT FROM ReservationCur INTO @Room_HallType, @BookedTypeNumber, @LINENUMBER, @RoomNumber, @ArrivalDate, @DepartureDate, @ProductNumber, @NumberOfRooms, @Status, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @PriceOverWritten, @Adults, @Children1, @Children2, @Price, 
      @ReferenceNumber, @PacketNumberReservation, @ArrArrivalTime, @ArrDepartureTime, @HotelCustomerNumber, @Plenum, @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber, @RoomTypeHotelNumber, @FK_ReferenceNumber, @IsTableBooking, @CountryNumber, @DepartmentNumber,
      @LArrivalTime, @LDepartureTime
    END --ConfLine

    IF @TableCount = 3 --no room, no hall
    BEGIN
      DECLARE ReservationCur CURSOR FAST_FORWARD READ_ONLY FOR
        SELECT DISTINCT CAST(3 AS TINYINT), r.ArrivalDate, r.DepartureDate, ISNULL(r.Status, 0), r.MarketSegment, r.PointOfSale, r.GuestType, r.PurposeCode, al.Price, r.ReferenceNumber, r.ArrivalTime, r.DepartureTime, ISNULL(Customer.CustomerNumber, - 1), 
          ISNULL(r.FK_CampaignCode, - 1), ISNULL(rm.FK_ProjectCode, - 1), ISNULL(rm.StaffID, - 1), r.SplitBill,
          ISNULL(CASE WHEN ReservationAddress.CountryNumber IS NULL THEN
            (SELECT TOP 1 CountryNumber FROM Countries WITH (NOLOCK) WHERE Countries.CountryCode = ReservationAddress.CountryCode)
          ELSE
            ReservationAddress.CountryNumber
          END, @HotelCountryNumber),
          ISNULL
          (
            (
              SELECT TOP 1 d.PK_Department
              FROM Departments d
              WHERE d.HotelNumber = ISNULL(Customer.HotelNumber, 0)
              AND ISNULL(d.MarkAsDeleted, 0) = 0 
              AND d.AutoCharge = 1        
            ),
            (
              ISNULL
              (
                (
                  SELECT TOP 1 d.PK_Department
                  FROM Departments d
                  WHERE d.HotelNumber = ISNULL(Customer.HotelNumber, 0)
                  AND ISNULL(d.MarkAsDeleted, 0) = 0 
                ),
                (
                  SELECT TOP 1 d.PK_Department
                  FROM Departments d
                  WHERE d.HotelNumber = ISNULL(Customer.HotelNumber, 0)
                )
              )
            )
          ),
          CASE WHEN ISDATE(al.Time) = 1 THEN CONVERT(DATETIME, al.Time, 108) ELSE 0 END, CASE WHEN ISDATE(al.DepartureTime) = 1 THEN CONVERT(DATETIME, al.DepartureTime, 108) ELSE 0 END
        FROM ArrangementLines al WITH (NOLOCK)
        INNER JOIN ArrangementReservationsXtab x WITH (NOLOCK) ON x.ArrangementLineNumber = al.ArrangementLineNumber
        INNER JOIN Reservations r WITH (NOLOCK) ON x.ReferenceNumber = r.ReferenceNumber
          AND ((@IncludeTentative = 0 AND r.Status IN (0, 1, 2, 5, 6, 7, 8)) OR (@IncludeTentative = 1 AND r.Status IN (0, 1, 2, 4, 5, 6, 7, 8)))
          AND r.ReferenceNumber > 0
        INNER JOIN ReservationMain rm WITH (NOLOCK) ON x.ReferenceNumber = rm.ReferenceNumber
        LEFT OUTER JOIN ReservationConferenceLine rc WITH (NOLOCK) ON rc.ReferenceNumber = rm.ReferenceNumber
        LEFT OUTER JOIN ReservationRoomLineXTab rr WITH (NOLOCK) ON rr.ReferenceNumber = rm.ReferenceNumber
        LEFT OUTER JOIN Customer WITH (NOLOCK) ON ISNULL(rm.HotelNumber, 0) = Customer.HotelNumber
          AND Customer.HotelNumber >= 0
          AND Customer.CustomerTypeNumber = 7
          AND ISNULL(Customer.MarkAsDeleted, 0) = 0
        LEFT JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.ReferenceNumber = r.ReferenceNumber
          AND ReservationAddressXTab.GuestNumber = r.GuestNumber
          AND ReservationAddressXTab.AddressTypeNumber = 1
        LEFT JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = ReservationAddressXTab.AddressNumber
          AND ReservationAddress.AddressType = 1
        WHERE ISNULL(rc.ReferenceNumber, - 1) = - 1 --Exclude halls
        AND ISNULL(rr.ReferenceNumber, - 1) = - 1 --Exclude rooms
        AND ((@CountResToRecalc = 0 AND r.DepartureDate >= @FormatedStartDate AND r.DepartureDate <= @CalcMISToDate) OR 
          r.Referencenumber IN (SELECT * FROM #ReservationsCrossDate WITH (NOLOCK)) OR 
          (r.Referencenumber IN (SELECT * FROM #ResToRecalc) AND r.DepartureDate >= @FormatedStartDate))
        AND NOT (ISNULL(r.RequestorID, 0) = - 2  AND ISNULL(rm.CreationInProgress, 0) = 1 AND r.Status = 7)
        ORDER BY r.ReferenceNumber
      OPEN ReservationCur

      FETCH NEXT FROM ReservationCur INTO @Room_HallType, @ArrivalDate, @DepartureDate, @Status, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @Price, @ReferenceNumber, @ArrArrivalTime, @ArrDepartureTime, @HotelCustomerNumber, @CampaignCode, @ProjectCode, @StaffID, 
      @SplitBillNumber, @CountryNumber, @DepartmentNumber, @LArrivalTime, @LDepartureTime
    END --no roomline, no hallline

    SET @PrevLineNumber = 0
    SET @PrevReferenceNumber = 0
    SET @GetVatValueFromProduct2 = 0
    SET @GetVatValueFromProduct3 = 0
    SET @GetVatValueFromProduct4 = 0
    SET @LineCounted = 0

    DECLARE @MainCourceNoValues BIT --should amounts, adults etc. be reset to 0

    IF @ShowTimeing = 1
    BEGIN
      PRINT 'Time 8'
      PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
      RAISERROR (N'', 0, 1) WITH NOWAIT
    END

    WHILE (@@FETCH_STATUS <> - 1)
    BEGIN
      SET @DepartmentNumber = ISNULL(@DepartmentNumber, -1)

      IF @ShowTimeing = 1
      BEGIN
        PRINT 'Time 9'
        PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
        RAISERROR (N'', 0, 1) WITH NOWAIT
      END

      IF @TableCount = 3 --no room, no hall
      BEGIN
        IF @ShowPrint = 1
          PRINT 'no room, no hall, Ref.=' + convert(VARCHAR, @ReferenceNumber)

        SET @BookedTypeNumber = 0
        SET @LINENUMBER = 0
        SET @RoomNumber = 0
        SET @ProductNumber = 0
        SET @NumberOfRooms = 0
        SET @PriceOverWritten = 0
        SET @Adults = 0
        SET @Children1 = 0
        SET @Children2 = 0
        SET @PacketNumberReservation = 0
        SET @Plenum = 0
        SET @OwnerReservation = 0
        SET @RoomTypeHotelNumber = 0
        SET @IsTableBooking = 0
        SET @FK_ReferenceNumber = 0
      END

      IF ( (ISNULL(@FK_ReferenceNumber, 0) = 0)  OR @MainCourceResNotInclMIS_OrderBook = 0)
        SET @MainCourceNoValues = 0
      ELSE
        SET @MainCourceNoValues = 1

      SET @TmpProductNumber = NULL

      IF ISNULL(@LINENUMBER, 0) = 0
        SET @LINENUMBER = 0

      SET @StarProduct = 0

      IF ISNULL(@ROOMNUMBER, 0) = 0
        SET @ROOMNUMBER = 0

      SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

      IF @TableCount = 2 --Hall
      BEGIN
        SET @guestnumber = 0
        SET @ConflineOnMainRes = 0
        SET @AllocatedTypeNumber = @BookedTypeNumber

        IF ISNULL(@BookedTypeNumber, 0) = 0
          SET @DepartureDate = CONVERT(CHAR(8), CONVERT(DATETIME, @DepartureDate) - 1, 112)

        IF ISNULL(@AllocatedTypeNumber, 0) = 0
          SET @AllocatedTypeNumber = 0

        IF (@ArrDepartureTime < @Arr24) AND (@BookedTypeNumber > 0)
          SET @DepartureDate = CONVERT(CHAR(8), CONVERT(DATETIME, @DepartureDate) - 1, 112)

        IF @ArrArrivalTime < @Arr24
          SET @ArrivalDate = CONVERT(CHAR(8), CONVERT(DATETIME, @ArrivalDate) - 1, 112)
      END

      IF @TableCount = 1 --Room
      BEGIN --Room
        SET @AllocatedTypeNumber = @BookedTypeNumber

        IF ISNULL(@Price, 0) = 0
          SET @Price = 0

        IF ISNULL(@TotalPrice, 0) = 0
          SET @TotalPrice = 0

        IF ISNULL(@Day2, 0) = 0
          SET @Day2 = 0

        IF ISNULL(@Day3, 0) = 0
          SET @Day3 = 0

        IF ISNULL(@Day4, 0) = 0
          SET @Day4 = 0

        IF ISNULL(@ProductNumber, 0) = 0
          SET @ProductNumber = 0

        IF ISNULL(@ProductNumber2, 0) = 0
          SET @ProductNumber2 = 0

        IF ISNULL(@ProductNumber3, 0) = 0
          SET @ProductNumber3 = 0

        IF ISNULL(@ProductNumber4, 0) = 0
          SET @ProductNumber4 = 0

        IF ISNULL(@AllocatedTypeNumber, 0) = 0
          SET @AllocatedTypeNumber = 0

        IF ((@Day2 + @Day3 + @Day4) > 0)
        BEGIN
          SET @StarProduct = 1

          IF @NameListSetting = 0
            SET @NameListSetting = @NameListSettingHotelSetup
        END
        ELSE
        BEGIN
          IF @ProductNumber > 0
          BEGIN
            IF @GuestNumber = 0
              SET @NameListSetting = 0

            IF @NameListSetting = 0
            BEGIN
              SELECT @NameListSetting = NameListSetting
              FROM Products WITH (NOLOCK)
              WHERE productnumber = @ProductNumber

              IF ISNULL(@NameListSetting, 0) = 0
                SET @NameListSetting = 0
            END
          END
          ELSE
            SET @NameListSetting = 0

          IF @NameListSetting = 0
            SET @NameListSetting = @NameListSettingHotelSetup
        END
      END --Room

      IF @TableCount = 3 --No room, no hall
        SET @AllocatedTypeNumber = 0

      IF ISNULL(@NumberOfRooms, 1) = 1
        SET @NumberOfRooms = 1

      IF ISNULL(@Adults, 0) = 0
        SET @Adults = 0

      IF ISNULL(@Children1, 0) = 0
        SET @Children1 = 0

      IF ISNULL(@Children2, 0) = 0
        SET @Children2 = 0

      IF (((@FirstFetch = 1) AND (@SameVAT = 1)) OR (@SameVAT = 0)) -- Find warenumber and acccountnumber for product   
      BEGIN
        SET @ThirdParam = CASE @GetVATFrom
            WHEN 0 THEN @SegmentNumber
            WHEN 1 THEN @PointOfSaleNumber
            WHEN 2 THEN @BookedTypeNumber -- Get Vat From Roomtype -- TODO ConferenceRoom if DayProduct
            WHEN 3 THEN @ProductNumber
            END

        EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ThirdParam, @WareNumberProduct OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct1 OUTPUT, @WareText OUTPUT, @WareGroupNumberProduct OUTPUT
      END

      IF ISNULL(@VatValueRoomProduct1, 0) = 0
        SET @VatValueRoomProduct1 = 0

      SET @CurrentDateStr = @ArrivalDate
      SET @CurrentDate = CONVERT(DATETIME, @CurrentDateStr)
      SET @CurrentDateStrDeparturePackage = CONVERT(CHAR(8), @CurrentDate - 1, 112)

      IF (@GuestNumber > 0) AND (@NameListSetting = 0)
      BEGIN
        SET @PaysAdults = @Adults
        SET @PaysChildren1 = @Children1
        SET @PaysChildren2 = @Children2
      END

      SET @TmpLineCounted = 0
      WHILE @CurrentDateStr <= @DepartureDate
      BEGIN
        SET @EnviromentFee = 0
        SET @VatByPacketValue = 0
        SET @PackagePrice = 0
        SET @VatValueRoomProduct2 = 0
        SET @VatValueRoomProduct3 = 0
        SET @VatValueRoomProduct4 = 0
        SET @PackagePriceProduct1 = 0
        SET @PackagePriceProduct2 = 0
        SET @PackagePriceProduct3 = 0
        SET @PackagePriceProduct4 = 0
        SET @VatByPacketValueProduct1 = 0
        SET @VatByPacketValueProduct2 = 0
        SET @VatByPacketValueProduct3 = 0
        SET @VatByPacketValueProduct4 = 0
        SET @PriceProduct1 = 0
        SET @PriceProduct2 = 0
        SET @PriceProduct3 = 0
        SET @PriceProduct4 = 0
        SET @Addon1 = 0
        SET @Addon2 = 0
        SET @Addon3 = 0
        SET @Addon4 = 0
        SET @ProductPriceDate = @CurrentDate

        DELETE FROM #PacketWareTable-- Clear #PacketWareTable

        --Now also status 7 and 8 shuold be included
        --IF @Status IN(0, 1, 2, 3, 4, 5, 6) -- NOT CPG -- Booked  -- NB Skal først få Booked til at virke !!! * product?   
        --BEGIN
        IF (@TableCount = 1) --room
        BEGIN
          SET @TotalPackagePrice = 0
          SET @TotalVatByPacketValue = 0

          DECLARE @AddressType TINYINT
          DECLARE @DiscountRate FLOAT

          EXEC FindFolioNumber @ReferenceNumber, @GuestNumber, 0, @WareNumber, @SplitbillNumber, 0, @FolioNumber OUTPUT, @AddressType OUTPUT   
          EXEC GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 1, @DiscountRate OUTPUT

          IF (@StarProduct = 0) -- Calc for not-+product   
          BEGIN
            SET @ProductStartDate = CONVERT(DATETIME, @ArrivalDate)
            SET @ProductEndDate = CONVERT(DATETIME, @DepartureDate)

            EXEC ProductPricesDay @ProductNumber, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, 
              @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

            SET @TmpProductNumber = @ProductNumber

            IF (@PriceOverWritten = 1)
            BEGIN
              IF (@CurrentDateStr <> @DepartureDate) OR (@ArrivalDate = @DepartureDate)
              BEGIN
                SET @PriceProduct1 = @Price * @NumberOfRooms
                SET @PriceOverwrittenValue = @Price

                IF @NameListSetting = 1 AND @OnePersonPaysForAll = 0
                BEGIN
                  SET @PriceProduct1 = @PriceProduct1 * (@Adults + @Children1 + @Children2)
                  SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2)
                END
              END
              ELSE
                SET @PriceOverwrittenValue = 0

              IF (@AddonIfPriceOverwritten = 0)
                SET @Addon1 = 0
            END

            IF (@CurrentDateStr <> @DepartureDate) OR (@ArrivalDate = @DepartureDate)
              SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

            IF @PacketNumber > 0
            BEGIN
              EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @NameListSetting, 
                @OnePersonPaysForAll, @PriceOverwritten, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, @DiscountRate, @ProductWareLinkNumber
            END
          END
          ELSE -- StarProduct = +product   
          BEGIN
            SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate)
            SET @TmpProductEndDate = CONVERT(DATETIME, @ArrivalDate) + @Day2 - 1

            --1. period
            IF ( @CurrentDate <= @TmpProductEndDate AND @PlusProductSamePeriod = 0) -- ProductNumber incl afrejse pakke    
              OR (@CurrentDate < @TmpProductEndDate AND @PlusProductSamePeriod = 1)
            BEGIN
              IF @PlusProductSamePeriod = 0 --old normal
              BEGIN
                SET @ProductStartDate = @TmpProductStartDate
                SET @ProductEndDate = @TmpProductEndDate
              END
              ELSE
              BEGIN
                SET @ProductStartDate = @TmpProductStartDate
                SET @ProductEndDate = CONVERT(DATETIME, @DepartureDate)--causing all days after arrivaldate to return stay package
              END

              IF @ShowPrint = 1
                PRINT '1. period ' + convert(VARCHAR, @PlusProductSamePeriod)

              EXEC ProductPricesDay @ProductNumber, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon1 OUTPUT, @BillTextProduct OUTPUT, 
                @BillTextAddOnProduct OUTPUT, @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

              SET @TmpProductNumber = @ProductNumber

              IF (@PriceOverWritten = 1)
              BEGIN
                IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                BEGIN
                  SET @PriceProduct1 = @FirstPrice1 * @NumberOfRooms
                  SET @PriceOverwrittenValue = @FirstPrice1

                  IF @NameListSetting = 1 AND @OnePersonPaysForAll = 0
                  BEGIN
                    SET @PriceProduct1 = @PriceProduct1 * (@Adults + @Children1 + @Children2)
                    SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2)
                  END
                END
                ELSE
                  SET @PriceOverwrittenValue = 0

                IF (@AddonIfPriceOverwritten = 0)
                  SET @Addon1 = 0
              END

              IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

              EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @NameListSetting, 
                @OnePersonPaysForAll, @PriceOverwritten, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, @DiscountRate, @ProductWareLinkNumber
            END

            --2.period
            IF (@Day3 = 0)
            BEGIN
              SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate) + @Day2 - 1
              SET @TmpProductEndDate = CONVERT(DATETIME, @DepartureDate)

              IF (@CurrentDate >= @TmpProductStartDate AND @PlusProductSamePeriod = 0) -- incl. afrejse pakke
                OR (@CurrentDate > @TmpProductStartDate AND @PlusProductSamePeriod = 1)
              BEGIN
                IF @PlusProductSamePeriod = 0
                BEGIN
                  SET @ProductStartDate = @TmpProductStartDate
                  SET @ProductEndDate = @TmpProductEndDate
                END
                ELSE
                BEGIN
                  SET @ProductStartDate = CONVERT(DATETIME, @ArrivalDate)--tvinger til at anvende stay for første dag i perioden
                  SET @ProductEndDate = @TmpProductEndDate
                END

                IF @ShowPrint = 1
                  PRINT '2. period, there is no 3. period'

                EXEC ProductPricesDay @ProductNumber2, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon2 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, 
                  @PriceProduct2 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

                SET @TmpProductNumber = @ProductNumber2

                IF (@PriceOverWritten2 = 1)
                BEGIN
                  IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                  BEGIN
                    SET @PriceProduct2 = @FirstPrice2 * @NumberOfRooms
                    SET @PriceOverwrittenValue = @FirstPrice2

                    IF @NameListSetting = 1 AND @OnePersonPaysForAll = 0
                    BEGIN
                      SET @PriceProduct2 = @PriceProduct2 * (@Adults + @Children1 + @Children2)
                      SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2)
                    END
                  END
                  ELSE
                    SET @PriceOverwrittenValue = 0

                  IF (@AddonIfPriceOverwritten = 0)
                    SET @Addon2 = 0
                END

                IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                  SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

                EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber2, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct2 OUTPUT, @VatByPacketValueProduct2 OUTPUT, @NameListSetting, 
                  @OnePersonPaysForAll, @PriceOverwritten2, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, @DiscountRate, @ProductWareLinkNumber

                SET @ThirdParam = CASE @GetVATFrom
                    WHEN 0 THEN @SegmentNumber
                    WHEN 1 THEN @PointOfSaleNumber
                    WHEN 2 THEN @BookedTypeNumber
                    WHEN 3 THEN @ProductNumber2
                    END

                EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ThirdParam, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct2 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT

                SET @GetVatValueFromProduct2 = 1
              END
            END
            ELSE --Still 2. period, but there is a 3. period
            BEGIN
              SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate) + @Day2 - 1
              SET @TmpProductEndDate = CONVERT(DATETIME, @ArrivalDate) + @Day3 - 1

              IF (@CurrentDate >= @TmpProductStartDate AND @CurrentDate <= @TmpProductEndDate AND @PlusProductSamePeriod = 0)
                OR (@CurrentDate >= @TmpProductStartDate AND @CurrentDate < @TmpProductEndDate AND @PlusProductSamePeriod = 1)
              BEGIN
                IF @PlusProductSamePeriod = 0
                BEGIN
                  SET @ProductStartDate = @TmpProductStartDate
                  SET @ProductEndDate = @TmpProductEndDate
                END
                ELSE
                BEGIN --force stay
                  SET @ProductStartDate = CONVERT(DATETIME, @ArrivalDate)
                  SET @ProductEndDate = @TmpProductEndDate
                END

                IF @ShowPrint = 1
                  PRINT '2. period, there is a 3. period'

                EXEC ProductPricesDay @ProductNumber2, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon2 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, 
                  @PriceProduct2 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

                SET @TmpProductNumber = @ProductNumber2

                IF (@PriceOverWritten2 = 1)
                BEGIN
                  IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                  BEGIN
                    SET @PriceProduct2 = @FirstPrice2 * @NumberOfRooms
                    SET @PriceOverwrittenValue = @FirstPrice2

                    IF @NameListSetting = 1 AND @OnePersonPaysForAll = 0
                    BEGIN
                      SET @PriceProduct2 = @PriceProduct2 * (@Adults + @Children1 + @Children2)
                      SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2)
                    END
                  END
                  ELSE
                    SET @PriceOverwrittenValue = 0

                  IF (@AddonIfPriceOverwritten = 0)
                    SET @Addon2 = 0
                END

                IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                  SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

                EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber2, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct2 OUTPUT, @VatByPacketValueProduct2 OUTPUT, @NameListSetting, 
                  @OnePersonPaysForAll, @PriceOverwritten2, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, @DiscountRate, @ProductWareLinkNumber

                SET @ThirdParam = CASE @GetVATFrom
                    WHEN 0 THEN @SegmentNumber
                    WHEN 1 THEN @PointOfSaleNumber
                    WHEN 2 THEN @BookedTypeNumber
                    WHEN 3 THEN @ProductNumber2
                    END

                EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ThirdParam, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct2 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT

                SET @GetVatValueFromProduct2 = 1
              END--IF(@CurrentDate >= @TmpProductStartDate) AND (@CurrentDate <= @TmpProductEndDate)

              IF (@Day4 = 0)
              BEGIN
                SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate) + @Day3 - 1
                SET @TmpProductEndDate = CONVERT(DATETIME, @DepartureDate)

                IF (@CurrentDate >= @TmpProductStartDate)
                BEGIN
                  IF @PlusProductSamePeriod = 0
                  BEGIN
                    SET @ProductStartDate = @TmpProductStartDate
                    SET @ProductEndDate = @TmpProductEndDate
                  END
                  ELSE
                  BEGIN
                    SET @ProductStartDate = CONVERT(DATETIME, @ArrivalDate) --force stay except last day
                    SET @ProductEndDate = @TmpProductEndDate
                  END

                  IF @ShowPrint = 1
                    PRINT '3. period, there is no 4. period'

                  EXEC ProductPricesDay @ProductNumber3, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon3 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, 
                    @PriceProduct3 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

                  SET @TmpProductNumber = @ProductNumber3

                  IF (@PriceOverWritten3 = 1)
                  BEGIN
                    IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                    BEGIN
                      SET @PriceProduct3 = @FirstPrice3 * @NumberOfRooms
                      SET @PriceOverwrittenValue = @FirstPrice3

                      IF @NameListSetting = 1 AND @OnePersonPaysForAll = 0
                      BEGIN
                        SET @PriceProduct3 = @PriceProduct3 * (@Adults + @Children1 + @Children2)
                        SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2)
                      END
                    END
                    ELSE
                      SET @PriceOverwrittenValue = 0

                    IF (@AddonIfPriceOverwritten = 0)
                      SET @Addon3 = 0
                  END

                  IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                    SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

                  EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber3, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct3 OUTPUT, @VatByPacketValueProduct3 OUTPUT, @NameListSetting, 
                    @OnePersonPaysForAll, @PriceOverwritten3, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, @DiscountRate, @ProductWareLinkNumber

                  SET @ThirdParam = CASE @GetVATFrom
                      WHEN 0 THEN @SegmentNumber
                      WHEN 1 THEN @PointOfSaleNumber
                      WHEN 2 THEN @BookedTypeNumber
                      WHEN 3 THEN @ProductNumber3
                      END

                  EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ThirdParam, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct3 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT

                  SET @GetVatValueFromProduct3 = 1
                END
              END--Day4 = 0
              ELSE
              BEGIN --still 3. period, but there is a 4. period
                SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate) + @Day3 - 1
                SET @TmpProductEndDate = CONVERT(DATETIME, @ArrivalDate) + @Day4 - 1

                IF (@CurrentDate >= @TmpProductStartDate AND @CurrentDate <= @TmpProductEndDate AND @PlusProductSamePeriod = 0)
                  OR (@CurrentDate >= @TmpProductStartDate AND @CurrentDate < @TmpProductEndDate AND @PlusProductSamePeriod = 1)
                BEGIN
                  IF @PlusProductSamePeriod = 0
                  BEGIN
                    SET @ProductStartDate = @TmpProductStartDate
                    SET @ProductEndDate = @TmpProductEndDate
                  END
                  ELSE
                  BEGIN
                    SET @ProductStartDate = CONVERT(DATETIME, @ArrivalDate) --Force stay
                    SET @ProductEndDate = @TmpProductEndDate
                  END

                  IF @ShowPrint = 1
                    PRINT '3. period, there is a 4. period'

                  EXEC ProductPricesDay @ProductNumber3, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon3 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, 
                    @PriceProduct3 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

                  SET @TmpProductNumber = @ProductNumber3

                  IF (@PriceOverWritten3 = 1)
                  BEGIN
                    IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                    BEGIN
                      SET @PriceProduct3 = @FirstPrice3 * @NumberOfRooms
                      SET @PriceOverwrittenValue = @FirstPrice3

                      IF @NameListSetting = 1 AND @OnePersonPaysForAll = 0
                      BEGIN
                        SET @PriceProduct3 = @PriceProduct3 * (@Adults + @Children1 + @Children2)
                        SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2)
                      END
                    END
                    ELSE
                      SET @PriceOverwrittenValue = 0

                    IF (@AddonIfPriceOverwritten = 0)
                      SET @Addon3 = 0
                  END

                  IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                  BEGIN
                    SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1
                  END

                  EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber3, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct3 OUTPUT, @VatByPacketValueProduct3 OUTPUT, @NameListSetting, 
                    @OnePersonPaysForAll, @PriceOverwritten3, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, @DiscountRate, @ProductWareLinkNumber

                  SET @ThirdParam = CASE @GetVATFrom
                      WHEN 0 THEN @SegmentNumber
                      WHEN 1 THEN @PointOfSaleNumber
                      WHEN 2 THEN @BookedTypeNumber
                      WHEN 3 THEN @ProductNumber3
                      END

                  EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ThirdParam, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct3 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT

                  SET @GetVatValueFromProduct3 = 1
                END--3. period
                --start 4. period

                SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate) + @Day4 - 1
                SET @TmpProductEndDate = CONVERT(DATETIME, @DepartureDate)

                IF (@CurrentDate >= @TmpProductStartDate) AND (@CurrentDate <= @TmpProductEndDate)
                BEGIN
                  IF @PlusProductSamePeriod = 0
                  BEGIN
                    SET @ProductStartDate = @TmpProductStartDate
                    SET @ProductEndDate = @TmpProductEndDate
                  END
                  ELSE
                  BEGIN
                    SET @ProductStartDate = CONVERT(DATETIME, @ArrivalDate) --force stay on 1. day in period
                    SET @ProductEndDate = @TmpProductEndDate
                  END

                  IF @ShowPrint = 1
                    PRINT '4. period'

                  EXEC ProductPricesDay @ProductNumber4, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon4 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, 
                    @PriceProduct4 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

                  SET @TmpProductNumber = @ProductNumber4

                  IF (@PriceOverWritten4 = 1)
                  BEGIN
                    IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                    BEGIN
                      SET @PriceProduct4 = @FirstPrice4 * @NumberOfRooms
                      SET @PriceOverwrittenValue = @FirstPrice4

                      IF @NameListSetting = 1 AND @OnePersonPaysForAll = 0
                      BEGIN
                        SET @PriceProduct4 = @PriceProduct4 * (@Adults + @Children1 + @Children2)
                        SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2)
                      END
                    END
                    ELSE
                      SET @PriceOverwrittenValue = 0

                    IF (@AddonIfPriceOverwritten = 0)
                      SET @Addon4 = 0
                  END

                  IF (@ProductStartDate <> @ProductEndDate) AND (@CurrentDate <> @ProductEndDate)
                    SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

                  EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber4, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct4 OUTPUT, @VatByPacketValueProduct4 OUTPUT, @NameListSetting, 
                    @OnePersonPaysForAll, @PriceOverwritten4, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, @DiscountRate, @ProductWareLinkNumber

                  SET @ThirdParam = CASE @GetVATFrom
                      WHEN 0 THEN @SegmentNumber
                      WHEN 1 THEN @PointOfSaleNumber
                      WHEN 2 THEN @BookedTypeNumber
                      WHEN 3 THEN @ProductNumber4
                      END

                  EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ThirdParam, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct4 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT

                  SET @GetVatValueFromProduct4 = 1
                END
              END--Day4 <> 0
            END--Day3 <> 0
          END-- END *-product   
        END -- end room

        IF (@TableCount = 2) --hall
        BEGIN
          SET @ProductStartDate = CONVERT(DATETIME, @ArrivalDate)--SG/20121218
          SET @ProductEndDate = CONVERT(DATETIME, @DepartureDate)--SG/20121218

          IF ((@PriceOverWritten = 0) AND (@ProductNumber > 0))
          BEGIN
            EXEC ProductPricesDay @ProductNumber, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct1 OUTPUT, 
              @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT

            SET @TmpProductNumber = @ProductNumber

            IF (@PacketNumber > 0)
              EXEC CalcPacketPriceAccExt 1, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber, @Adults, @Children1, @Children2, 1, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, 1, 0, @PriceOverwritten, 
                @FixedPrice, 1, @Referencenumber, @GuestNumber, @PriceProduct1, 0, @ProductWareLinkNumber
            ELSE
            BEGIN
              SET @PackagePriceProduct1 = 0
              SET @VatByPacketValueProduct1 = 0
            END
          END
          ELSE
          BEGIN
            IF @ProductNumber > 0
            BEGIN
              EXEC ProductPricesDay @ProductNumber, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct1 OUTPUT, 
                @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT

              SET @TmpProductNumber = @ProductNumber

              IF @FixedPrice = 1
              BEGIN
                IF (@PriceOverWritten = 1)
                BEGIN
                  IF ISNULL(@Price, 0) = 0
                    SET @Price = 0

                  SET @PriceProduct1 = @Price * @NumberOfRooms
                END
              END
              ELSE
              BEGIN
                IF (@PriceOverWritten = 1)
                BEGIN
                  IF ISNULL(@Price, 0) = 0
                    SET @Price = 0

                  SET @PriceProduct1 = (CONVERT(MONEY, (@Price * @Adults)) + CONVERT(MONEY, (@Price * @Children1)) + CONVERT(MONEY, (@Price * @Children2))) * @NumberOfRooms
                END
              END

              IF (@PacketNumber > 0)
              BEGIN
                EXEC CalcPacketPriceAccExt 1, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber, @Adults, @Children1, @Children2, 1, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, 1,0, @PriceOverwritten, 
                  0, 1, @Referencenumber, @GuestNumber, @PriceProduct1, 0, @ProductWareLinkNumber
              END
              ELSE
              BEGIN
                SET @PackagePriceProduct1 = 0
                SET @VatByPacketValueProduct1 = 0
              END
            END
            ELSE --    
            BEGIN
              SET @FixedPrice = 0
              SET @PriceProduct1 = @Price * @NumberOfRooms * (@Adults + @Children1 + @Children2)
              SET @PacketNumber = @PacketNumberReservation

              IF (@PacketNumberReservation > 0)
              BEGIN
                EXEC CalcPacketPriceAccExt 1, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumberReservation, @ProductNumber, @Adults, @Children1, @Children2, 1, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, 1, 0, @PriceOverwritten, 
                  0, 1, @Referencenumber, @GuestNumber, @PriceProduct1, 0, @ProductWareLinkNumber
              END
              ELSE
              BEGIN
                SET @PackagePriceProduct1 = 0
                SET @VatByPacketValueProduct1 = 0
              END
            END
          END

          IF @FixedPrice = 0
            SET @ValueType = 3
          ELSE
            SET @ValueType = 2
        END-- End DayProduct  

        IF (@TableCount = 3) AND @ShowPrint = 1 --no room, no hall
          PRINT 'No room, no hall'

        --END -- END Booked values   
        IF (@CurrentDateStr = @DepartureDate) AND (@ArrivalDate <> @DepartureDate) AND (@TableCount = 1)
        BEGIN
          IF ((@IncludeDayroomsInSoldRooms = 1) AND (@DepartureTime > @DayroomsLaterThanTime)) AND (@CurrentDateStr < @SystemDateStr)
          BEGIN
            IF @PrevLineNumber = @LineNumber
              AND @PrevReferenceNumber = @ReferenceNumber
              AND @PrevGuestNumber <> @GuestNumber
              AND @LineCounted = 1
              AND @TableCount = 1
              AND @SmallestArrivalDate <= @CurrentDateStr
              AND (((@BiggestDepartureDate >= @CurrentDateStr) AND (@DepartureDate <= @BiggestDepartureDate))
                OR ((@BiggestDepartureDate > @CurrentDateStr) AND (@DepartureDate > @BiggestDepartureDate)))
              AND @ArrivalDate >= @SmallestArrivalDate
            BEGIN
              SET @BookedNumberOfRooms = 0--Sharing same room
            END
            ELSE
            BEGIN
              SET @BookedNumberOfRooms = @NumberOfRooms
              IF @NumberOfRooms > 0 AND @Status NOT IN (7, 8)
                SET @TmpLineCounted = 1
            END

            SET @TotalAdults = @Adults * @NumberOfRooms
            SET @TotalChildren1 = @Children1 * @NumberOfRooms
            SET @TotalChildren2 = @Children2 * @NumberOfRooms
          END
          ELSE
          BEGIN
            SET @TotalAdults = 0
            SET @TotalChildren1 = 0
            SET @TotalChildren2 = 0
            SET @BookedNumberOfRooms = 0
          END

          SET @PriceProduct1 = 0
          SET @PriceProduct2 = 0
          SET @PriceProduct3 = 0
          SET @PriceProduct4 = 0

          IF @StarProduct = 0
          BEGIN
            SET @PackagePrice = @PackagePriceProduct1 * @NumberOfRooms
            SET @VatOfPacket = @VatByPacketValueProduct1 * @NumberOfRooms
            SET @VatOfPrice = @PriceProduct1 * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1))))
            SET @VatOfAddon = @Addon1 * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1))))
          END
          ELSE
          BEGIN
            SET @VatOfPrice = (((@PriceProduct1) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1)))) + (@PriceProduct2) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct2 / 100) + 1)))) + (@PriceProduct3) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct3 / 100) + 1)))) + (@PriceProduct4) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct4 / 100) + 1))))))
            SET @PackagePrice = (@PackagePriceProduct1 + @PackagePriceProduct2 + @PackagePriceProduct3 + @PackagePriceProduct4) * @NumberOfRooms
            SET @VatOfPacket = (@VatByPacketValueProduct1 + @VatByPacketValueProduct2 + @VatByPacketValueProduct3 + @VatByPacketValueProduct4) * @NumberOfRooms
            SET @VatOfAddon = (((@Addon1) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1)))) + (@Addon2) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct2 / 100) + 1)))) + (@Addon3) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct3 / 100) + 1)))) + (@Addon4) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct4 / 100) + 1))))))
          END
        END--sidste dag af flere
        ELSE
        BEGIN
          IF @PrevLineNumber = @LineNumber
            AND @PrevReferenceNumber = @ReferenceNumber
            AND @PrevGuestNumber <> @GuestNumber
            AND @LineCounted = 1
            AND @TableCount = 1
            AND @SmallestArrivalDate <= @CurrentDateStr
            AND (((@BiggestDepartureDate >= @CurrentDateStr) AND (@DepartureDate <= @BiggestDepartureDate))
              OR ((@BiggestDepartureDate > @CurrentDateStr) AND (@DepartureDate > @BiggestDepartureDate)))
            AND @ArrivalDate >= @SmallestArrivalDate
          BEGIN
            SET @BookedNumberOfRooms = 0--Sharing same room
          END
          ELSE
          BEGIN
            SET @BookedNumberOfRooms = @NumberOfRooms
            IF @NumberOfRooms > 0 AND @Status NOT IN (7, 8)
              SET @TmpLineCounted = 1
          END

          IF ISNULL(@PriceProduct1, 0) = 0
            SET @PriceProduct1 = 0

          IF ISNULL(@PriceProduct2, 0) = 0
            SET @PriceProduct2 = 0

          IF ISNULL(@PriceProduct3, 0) = 0
            SET @PriceProduct3 = 0

          IF ISNULL(@PriceProduct4, 0) = 0
            SET @PriceProduct4 = 0

          IF ISNULL(@Addon1, 0) = 0
            SET @Addon1 = 0

          IF ISNULL(@Addon2, 0) = 0
            SET @Addon2 = 0

          IF ISNULL(@Addon3, 0) = 0
            SET @Addon3 = 0

          IF ISNULL(@Addon4, 0) = 0
            SET @Addon4 = 0

          IF ISNULL(@NumberOfRooms, 0) = 0
            SET @NumberOfRooms = 1

          IF ((@TableCount = 2) OR ((@StarProduct = 0) AND (@TableCount = 1)))
          BEGIN
            SET @PackagePrice = @PackagePriceProduct1 * @NumberOfRooms
            SET @VatOfPacket = @VatByPacketValueProduct1 * @NumberOfRooms
            SET @VatOfPrice = ((@PriceProduct1) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1)))))--* @NumberOfRooms
            SET @VatOfAddon = @Addon1 * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1))))
          END
          ELSE
          BEGIN
            SET @VatOfPrice = (((@PriceProduct1) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1)))) + (@PriceProduct2) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct2 / 100) + 1)))) + (@PriceProduct3) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct3 / 100) + 1)))) + (@PriceProduct4 + @Addon4) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct4 / 100) + 1))))))--* @NumberOfRooms
            SET @PackagePrice = (@PackagePriceProduct1 + @PackagePriceProduct2 + @PackagePriceProduct3 + @PackagePriceProduct4) * @NumberOfRooms
            SET @VatOfPacket = (@VatByPacketValueProduct1 + @VatByPacketValueProduct2 + @VatByPacketValueProduct3 + @VatByPacketValueProduct4) * @NumberOfRooms
            SET @VatOfAddon = (((@Addon1) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1)))) + (@Addon2) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct2 / 100) + 1)))) + (@Addon3) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct3 / 100) + 1)))) + (@Addon4) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct4 / 100) + 1))))))
          END

          SET @TotalAdults = @Adults * @NumberOfRooms
          SET @TotalChildren1 = @Children1 * @NumberOfRooms
          SET @TotalChildren2 = @Children2 * @NumberOfRooms
        END

        IF ISNULL(@SegmentNumber, 0) = 0
          SET @SegmentNumber = 0

        IF (@SegmentNumber = 0)
        BEGIN
          SELECT @SegmentNumber = Number
          FROM Segments WITH (NOLOCK)
          WHERE ((MarkAsDeleted = '0') OR (MarkAsDeleted IS NULL))
        END

        IF ISNULL(@PointOfSaleNumber, 0) = 0
          SET @PointOfSaleNumber = 0

        IF (@PointOfSaleNumber = 0)
        BEGIN
          SELECT @PointOfSaleNumber = Number
          FROM PointOfSales WITH (NOLOCK)
          WHERE ((MarkAsDeleted = '0') OR (MarkAsDeleted IS NULL))
        END

        IF ISNULL(@GuestType, 0) = 0
          SET @GuestType = @DefaultMISGuestType

        IF ISNULL(@PurposeCode, 0) = 0
          SET @PurposeCode = @DefaultMISPurposeCode

        SET @TotalPriceDay = @PriceProduct1 + @PriceProduct2 + @PriceProduct3 + @PriceProduct4-- + @Addon1 + @Addon2 + @Addon3 + @Addon4
        SET @Addon = @Addon1 + @Addon2 + @Addon3 + @Addon4
        SET @tmpProductWareLinkNumberMis = @ProductWareLinkNumber

        IF ((@Status = 6) OR (@Status = 5))
          AND (@CurrentDate < @SystemDate) -- Only resolve pieces and pax when outofhouse and inhouse reservation before systemdate and on systemdate
        BEGIN
          SET @TotalPriceDay = 0
          SET @VatOfPrice = 0
          SET @Addon = 0
          SET @VatOfAddon = 0
          --set @TmpProductNumber = null
          SET @tmpProductWareLinkNumberMis = - 1
        END

        IF (@CurrentDate < @SystemDate - 1)
          DELETE FROM #PacketWareTable

        --*** Extras start
        SELECT @cnt = COUNT(*)
        FROM #ReferenceExtrasTable(NOLOCK)
        WHERE ReferenceNumber = @ReferenceNumber
        AND CurrentDate = @CurrentDateStr

        IF (ISNULL(@cnt, 0) = 0) AND (@CurrentDateStr >= @SystemDateStr)
        BEGIN
          EXEC MisStoreExtrasAndCalcDiscount @OrderBookBudgetCalcDiscount, @DiscountAsNettoPrice, @ChargeDiscountAsProduct, @DiscountVatValueWare, @Room_HallType, @ReferenceNumber, @FolioNumber, @CurrentDateStr, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @AllocatedTypeNumber, 
            @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @DiscountResultAccountNumber, @DiscountMISValueType, @DiscountWareNumber, @SplitBillNumber, @CountryNumber

          INSERT INTO #ReferenceExtrasTable
          VALUES (@ReferenceNumber, @CurrentDateStr)
        END

        --**** Extras end
        IF (@CurrentDateStr < @SystemDateStr)
        BEGIN
          IF (@Plenum = 0)
            SET @tmpUpdateType = 1
          ELSE
            SET @tmpUpdateType = 2--actual
        END
        ELSE
        BEGIN
          IF (@Plenum = 0)
            SET @tmpUpdateType = 3
          ELSE
            SET @tmpUpdateType = 4--booked
        END

        IF @TableCount = 1 AND @PackageSameDayAsLogi = 1 AND @CurrentDateStr = @DepartureDate
          SET @tmpSameDayAsLogi = 1
        ELSE
          SET @tmpSameDayAsLogi = 0

        -- Store Logi
        IF @MainCourceNoValues = 1
        BEGIN
          IF @ShowPrint = 1
            PRINT 'MAIN COURSE ' + CONVERT(VARCHAR, @Referencenumber) + ', ' + CONVERT(VARCHAR, @TotalAdults) + ', ' + CONVERT(VARCHAR, @TotalPriceDay)

          SET @BookedNumberOfRooms = 0
          SET @TotalAdults = 0
          SET @TotalChildren1 = 0
          SET @TotalChildren2 = 0
          SET @TotalPriceDay = 0
          SET @VatOfPrice = 0
          SET @PackagePrice = 0
          SET @VatOfPacket = 0
        END

        SET @ResultAccountNumber = ISNULL(@ResultAccountNumber, - 1)

        IF @ArrivalDate = @CurrentDateStr
          SET @TheArrivalTime = @LArrivalTime
        ELSE
          SET @TheArrivalTime = CAST(0 AS DATETIME)
        IF @DepartureDate = @CurrentDateStr
          SET @TheDepartureTime = @LDepartureTime
        ELSE
          SET @TheDepartureTime = CAST('23:59:59.997' AS DATETIME)

        EXEC MisStoreLogiAndCalcDiscount @Room_HallType, @OrderBookBudgetCalcDiscount, @DiscountAsNettoPrice, @ChargeDiscountAsProduct, @DiscountVatValueWare, @SplitBillNumber, @FixedPrice, @tmpUpdateType, @tmpSameDayAsLogi, @ValueType, @BookedNumberOfRooms, 
          @TotalAdults, @TotalChildren1, @TotalChildren2, @ReferenceNumber, @GuestNumber, @SystemDateStr, @CurrentDateStr, @CurrentDateStrDeparturePackage, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @AllocatedTypeNumber, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, 
          @StaffID, @WareGroupNumberProduct, @WareNumberProduct, @OwnerReservation, @DepartmentNumber, @tmpProductWareLinkNumberMis, @ResultAccountNumber, @DiscountResultAccountNumber, @TotalPriceDay, @VatOfPrice, @PackagePrice, @VatOfPacket, @TmpProductNumber, 
          @DiscountMISValueType, @DiscountWareNumber, @CountryNumber, @TheArrivalTime, @TheDepartureTime

        -- Store addons
        IF (@Addon <> 0 OR @VatOfAddon <> 0) AND (@MainCourceNoValues = 0)
        BEGIN
          SET @TempCurrentDateStr = @CurrentDateStr

          IF @Room_HallType = 0
          BEGIN
            IF (@CurrentDateStr = @DepartureDate)
              SET @TempCurrentDateStr = CONVERT(CHAR(8), @CurrentDate - 1, 112)
          END

          DECLARE @tmpAddOnWareNumber INT
          DECLARE @tmpAddonWareType INT
          DECLARE @tmpAddonAccountNumber INT

          SET @tmpAddOnWareNumber = @AddonWareNumber
          SET @tmpAddonWareType = @AddonWareType
          SET @tmpAddonAccountNumber = @AddonResultAccountNumber

          IF @AddonAsWare = 1
          BEGIN
            SET @tmpAddOnWareNumber = @WareNumber

            SELECT @tmpAddonWareType Type
            FROM Ware WITH (NOLOCK)
            WHERE WareNumber = @WareNumber
          END

          IF @ChargeAddonAsProduct = 1
            SET @tmpAddonAccountNumber = @ResultAccountNumber

          DECLARE @TotalPax INT = @TotalAdults + @TotalChildren1 + @TotalChildren2

          EXEC UpdateMISTable @SystemDateStr, @Room_HallType, @ReferenceNumber, @GuestNumber, @tmpUpdateType, @tmpSameDayAsLogi, 0, 0, 0, 0, @Addon, @VatOfAddon, 0, 0, @TempCurrentDateStr, @CurrentDateStrDeparturePackage, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode,
            @AllocatedTypeNumber, @ValueType, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @WareGroupNumber, @tmpAddonAccountNumber, @DepartmentNumber, - 1, 0, @AddonWareText, @OwnerReservation, @TmpProductNumber, 
            @tmpAddonWareType, @tmpAddOnWareNumber, @TotalPax, @CountryNumber, @TheArrivalTime, @TheDepartureTime
        END

        DECLARE @DayProductLocal BIT

        IF @TableCount = 1 --Room
          SET @DayProductLocal = 0
        ELSE
          SET @DayProductLocal = 1

        IF (@CurrentDate < @SystemDate - 1)
        BEGIN
          IF (@Plenum = 0)
            SET @tmpUpdateType = 1
          ELSE
            SET @tmpUpdateType = 2
        END
        ELSE
        BEGIN
          IF (@Plenum = 0)
            SET @tmpUpdateType = 3
          ELSE
            SET @tmpUpdateType = 4
        END

        --per reservation, per day
        EXEC MISCalcProvision @SystemDateStr, @CurrentDateStr, @CurrentDateStrDeparturePackage, @Room_HallType, @ReferenceNumber, @GuestNumber, @TotalPriceDay, @Addon, @DayProductLocal, @tmpUpdateType, @SplitBillNumber, @Room_HallType, @PackageSameDayAsLogi, @SegmentNumber, 
          @PointOfSaleNumber, @GuestType, @PurposeCode, @AllocatedTypeNumber, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @DepartmentNumber, @ProductWareLinkNumber, 0, @Text, @OwnerReservation, @ProductNumber, @CountryNumber, @TheArrivalTime, @TheDepartureTime

        -- Store Packages
        DECLARE PacketWareCur CURSOR FAST_FORWARD READ_ONLY FOR
          SELECT *
          FROM #PacketWareTable WITH (NOLOCK)
        OPEN PacketWareCur

        FETCH NEXT FROM PacketWareCur INTO @ResultAccountPackage, @DepartmentNumberPackage, @PacketWarePrice, @VatOfPacketWarePrice, @WareGroupNumber, @WareName, @WareType, @WareNumber, @ProductWareLinkNumberMis, @ProductNumberPacket, @BookedWareCountPacket, @HotelCustomerNumber, @LFromTime, @LToTime

        IF (@CurrentDate >= @SystemDate)
        BEGIN
          SET @PackageStored = 0

          IF (@@FETCH_STATUS <> - 1)
            SET @PackageStored = 1

          WHILE (@@FETCH_STATUS <> - 1)
          BEGIN
            IF (@CurrentDate = @SystemDate)
            BEGIN
              IF @TableCount = 2  OR @SystemDate < @ProductEndDate
                SET @ProductWareLinkNumberMis = - 200 -- Later in MisUpdateProductWareLinkNumbers this packet will be pared with product that is already posted in actual
              ELSE
                SET @ProductWareLinkNumberMis = - 100
            END

            SET @DepartmentNumberPackage = ISNULL(@DepartmentNumberPackage, - 1)
            SET @ResultAccountPackage = ISNULL(@ResultAccountPackage, - 1)

            IF (@PacketWarePrice <> 0 OR @VatOfPacketWarePrice <> 0 OR @BookedWareCountPacket <> 0) AND (@MainCourceNoValues = 0)
            BEGIN
              SET @PacketWarePrice = @PacketWarePrice * @NumberOfRooms
              SET @VatOfPacketWarePrice = @VatOfPacketWarePrice * @NumberOfRooms
              SET @BookedWareCountPacket = @BookedWareCountPacket * @NumberOfRooms

              IF @ProductWareLinkNumberMis <> - 100 -- SG/20130124: See above
              BEGIN
                EXEC UpdateMISTable @SystemDateStr, @Room_HallType, @ReferenceNumber, @GuestNumber, @tmpUpdateType, @tmpSameDayAsLogi, 0, 0, 0, 0, 0, 0, @VatOfPacketWarePrice, @PacketWarePrice, @CurrentDateStr, @CurrentDateStrDeparturePackage, @SegmentNumber, 
                  @PointOfSaleNumber, @GuestType, @PurposeCode, @AllocatedTypeNumber, @ValueType, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @WareGroupNumber, @ResultAccountPackage, @DepartmentNumberPackage, @ProductWareLinkNumberMis, 1, @WareName, 
                  @OwnerReservation, @ProductNumberPacket, @WareType, @WareNumber, @BookedWareCountPacket, @CountryNumber, @LFromTime, @LToTime

                EXEC MISCalcProvision @SystemDateStr, @CurrentDateStr, @CurrentDateStrDeparturePackage, @Room_HallType, @ReferenceNumber, @GuestNumber, @PacketWarePrice, 0, @DayProductLocal, @tmpUpdateType, @SplitBillNumber, @Room_HallType, @PackageSameDayAsLogi, 
                  @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @AllocatedTypeNumber, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @DepartmentNumber, @ProductWareLinkNumber, 1, @Text, @OwnerReservation, @ProductNumber, @CountryNumber, @LFromTime, @LToTime
              END
            END

            FETCH NEXT FROM PacketWareCur INTO @ResultAccountPackage, @DepartmentNumberPackage, @PacketWarePrice, @VatOfPacketWarePrice, @WareGroupNumber, @WareName, @WareType, @WareNumber, @ProductWareLinkNumberMis, @ProductNumberPacket, @BookedWareCountPacket, @HotelCustomerNumber, @LFromTime, @LToTime
          END
        END

        IF (@TableCount <> 1)
          SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

        CLOSE PacketWareCur
        DEALLOCATE PacketWareCur

        SET @CurrentDate = @CurrentDate + 1
        SET @CurrentDateStr = CONVERT(CHAR(8), @CurrentDate, 112)
        SET @CurrentDateStrDeparturePackage = CONVERT(CHAR(8), @CurrentDate - 1, 112)
      END-- End While @CurrentDateStr <= @DepartureDate   
      IF @TmpLineCounted = 1
        SET @LineCounted = @TmpLineCounted

      IF @LINENUMBER = @PrevLineNumber
      BEGIN
        IF @ArrivalDate < @SmallestArrivalDate
          SET @SmallestArrivalDate = @ArrivalDate

        IF @BiggestDepartureDate < @DepartureDate
          SET @BiggestDepartureDate = @DepartureDate
      END
      ELSE
      BEGIN
        SET @SmallestArrivalDate = @ArrivalDate
        SET @BiggestDepartureDate = @DepartureDate
      END

      SET @PrevLineNumber = @LINENUMBER
      SET @PrevReferenceNumber = @ReferenceNumber

      IF @TableCount = 1 -- 1=roomline
      BEGIN
        SET @PrevGuestNumber = @GuestNumber

        FETCH NEXT FROM ReservationCur INTO @Room_HallType, @LINENUMBER, @BookedTypeNumber, @RoomNumber, @ReferenceNumber, @GuestNumber, @Status, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @ArrivalDate, @DepartureDate, @DepartureTime, @Adults, @Children1, @Children2, 
          @PaysAdults, @PaysChildren1, @PaysChildren2, @ProductNumber, @NumberOfRooms, @PriceOverwritten, @Price, @FirstPrice1, @PriceOverwritten2, @FirstPrice2, @Day2, @ProductNumber2, @PriceOverwritten3, @FirstPrice3, @Day3, @ProductNumber3, @PriceOverwritten4, 
          @FirstPrice4, @Day4, @ProductNumber4, @ConferenceLineOnRes, @ConflineOnMainRes, @HotelCustomerNumber, @NameListSetting, @Plenum, @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber, @RoomTypeHotelNumber, @FK_ReferenceNumber, @PlusProductSamePeriod, 
          @CountryNumber, @DepartmentNumber, @LArrivalTime, @LDepartureTime
      END

      IF @TableCount = 2 -- 2=hall
        FETCH NEXT FROM ReservationCur INTO @Room_HallType, @BookedTypeNumber, @LINENUMBER, @RoomNumber, @ArrivalDate, @DepartureDate, @ProductNumber, @NumberOfRooms, @Status, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @PriceOverWritten, @Adults, @Children1, @Children2, @Price, 
          @ReferenceNumber, @PacketNumberReservation, @ArrArrivalTime, @ArrDepartureTime, @HotelCustomerNumber, @Plenum, @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber, @RoomTypeHotelNumber, @FK_ReferenceNumber, @IsTableBooking, @CountryNumber, @DepartmentNumber,
          @LArrivalTime, @LDepartureTime

      IF @TableCount = 3 -- 3= No room, no hall
        FETCH NEXT FROM ReservationCur INTO @Room_HallType, @ArrivalDate, @DepartureDate, @Status, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @Price, @ReferenceNumber, @ArrArrivalTime, @ArrDepartureTime, @HotelCustomerNumber, @CampaignCode, @ProjectCode, @StaffID, 
        @SplitBillNumber, @CountryNumber, @DepartmentNumber, @LArrivalTime, @LDepartureTime

      IF @PrevLineNumber <> @LineNumber
        SET @LineCounted = 0
    END-- Fetch ReservationCur  

    IF @ShowTimeing = 1
    BEGIN
      PRINT 'Time 10'
      PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
      RAISERROR (N'', 0, 1) WITH NOWAIT
    END

    CLOSE ReservationCur
    DEALLOCATE ReservationCur
  END-- END WHILE  
END--IF @CalcSystemDateOnly = 0 

IF @ShowPrint = 1
BEGIN
  PRINT '***************** Transaction section ************************'
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

DECLARE @Debit BIT
DECLARE @TransactionNumber INT
DECLARE @VatValueWare FLOAT
DECLARE @MisType INT--WareGroups.WareType
DECLARE @WarePayment SMALLINT
DECLARE @Totalsum MONEY
DECLARE @TransDate CHAR(8)
DECLARE @tmpTransdate CHAR(8)
DECLARE @ShowOnBillFlag BIT
DECLARE @TransactionMoved BIT
DECLARE @TransactionDeleted BIT
DECLARE @IsRoom BIT = 0
DECLARE @IsHall BIT = 0
DECLARE @RelatedMisType INT
DECLARE @RelatedWarePayment SMALLINT
DECLARE @TranNote VARCHAR(50)
DECLARE @MovedReferenceNumber INT
DECLARE @MovedGuestNumber INT
DECLARE @gtn INT

IF (@CalcSystemDateOnly = 1)
  SET @FormatedStartDate = @SystemDateStr

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 11'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

-- Part that consider Sales and invoice folios
--IF @CountResToRecalc = 0 --Normal MIS-calculation
--BEGIN
DECLARE TransCur CURSOR FAST_FORWARD READ_ONLY FOR
  SELECT DISTINCT CONVERT(CHAR(8), Transactions.DateStamp, 112) AS OriginalDate, ISNULL(Folios.Referencenumber, - 1) AS Referencenumber,
  CASE WHEN Folios.FolioNumber = - 1 THEN - 99 ELSE Folios.FolioNumber END AS FolioNumber, 
  CASE WHEN Transactions.Debit = 0 THEN Transactions.PriceOverwrite ELSE (Transactions.PriceOverwrite * - 1) END AS SumTotal, 
  CASE WHEN (ISNULL(Reservations.MarketSegment, 0) = 0) THEN ISNULL(Customer.SegmentNumber, 0) ELSE Reservations.MarketSegment END AS MarketSegment, 
  CASE WHEN (ISNULL(Reservations.PointOfSale, 0) = 0) THEN ISNULL(Customer.PointOfSaleNumber, 0) ELSE Reservations.PointOfSale END AS PointOfSale, 
  Reservations.GuestType,
  CASE WHEN (ISNULL(Reservations.PurposeCode, 0) = 0) THEN Customer.PurposeCodeNumber ELSE Reservations.PurposeCode END, 
  WareGroups.WareType AS MISType, WareGroups.Payment, Transactions.VATValue, Transactions.HotelCustomerNumber, ISNULL(CAST(Reservations.Status AS INT), - 1) AS ReservationStatus, 
  ISNULL(Reservations.FK_CampaignCode, - 1) AS CampaignCode, ISNULL(Folios.FkProjectCode, ISNULL(ReservationMain.FK_ProjectCode, - 1)) AS ProjectCode, Transactions.UserIDNumber AS StaffID, 
  CASE WHEN ISNULL(Transactions.PackageNumber, - 1) > 0 AND Transactions.ShowOnBillFlag = 0 AND Transactions.ProductWareLinkNumber > 0 AND WareGroups.Payment NOT IN (2, 3) THEN 1 ELSE 0 END AS IsPackage, 
  WareGroups.SortNumber AS WareGroupNumber, Transactions.TransactionNumber, ISNULL(Transactions.PAXadult, 0) AS PAXAdult, ISNULL(Transactions.PAXchild1, 0) AS PAXchild1, ISNULL(Transactions.PAXchild2, 0) AS PAXchild2, 
  Transactions.Pieces, Transactions.Debit, Transactions.ProductNumber, ISNULL(Transactions.ProductWareLinkNumber, - 1) AS PWLN, Transactions.AccountNumber, Transactions.ShowOnBillFlag, Transactions.FK_DepartmentNumber, 
  ISNULL(Transactions.GuestNumber, 0) AS GuestNumber, Products.FixedPrice, Products.DayProduct,
  CASE WHEN (Transactions.MovedDeleted = 1 AND Transactions.MovedFolioNr IS NOT NULL)  THEN 1 ELSE 0 END AS Moved, 
  CASE WHEN (Transactions.MovedDeleted = 1 AND Transactions.MovedFolioNr IS NULL) THEN 1 ELSE 0 END AS Deleted, 
  FK_ReferenceNumber, Ware.Type AS WareType, Ware.WareNumber, Ware.WareName,
  CASE WHEN Products.DayProduct = 1 THEN 0 ELSE 1 END AS IsRoom,
  Products.DayProduct AS IsHall, Transactions.GlobalTransactionNumber,
  ISNULL(LTRIM(RTRIM(Transactions.Note)), ''),
  (
    SELECT TOP 1 F.ReferenceNumber
    FROM Folios F WITH (NOLOCK)
    WHERE F.FolioNumber = Transactions.MovedFolioNr  
  ) AS MovedReferenceNumber,
  (
    SELECT TOP 1 F.GuestNumber
    FROM Folios F WITH (NOLOCK)
    WHERE F.FolioNumber = Transactions.MovedFolioNr  
  ) AS MovedGuestNumber,
  ISNULL(CASE WHEN ReservationAddress.CountryNumber IS NULL THEN
  (SELECT TOP 1 CountryNumber FROM Countries WITH (NOLOCK) WHERE Countries.CountryCode = ReservationAddress.CountryCode)
  ELSE
    ReservationAddress.CountryNumber
  END, @HotelCountryNumber), FolioRestResTableChairsXTab.RestaurantReservationNumber,
  CASE WHEN ISNULL(TransactionPeriod.FromDateTime, 0) > 0 THEN CAST(TransactionPeriod.FromDateTime AS TIME) ELSE CAST(Transactions.DateStamp AS TIME) END,
  CASE WHEN ISNULL(TransactionPeriod.ToDateTime, 0) > 0 THEN CAST(TransactionPeriod.ToDateTime AS TIME) ELSE CAST(0 AS DATETIME) END
  FROM Transactions WITH (NOLOCK)
  INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = Transactions.FolioNumber
  LEFT OUTER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = Folios.ReservationAddressNumber
  LEFT OUTER JOIN Customer WITH (NOLOCK) ON Customer.CustomerNumber = ReservationAddress.Link
  LEFT OUTER JOIN Reservations WITH (NOLOCK) ON Folios.ReferenceNumber = Reservations.ReferenceNumber
    AND Folios.GuestNumber = Reservations.GuestNumber
  LEFT OUTER JOIN ReservationMain WITH (NOLOCK) ON ReservationMain.ReferenceNumber = Folios.ReferenceNumber
  INNER JOIN Ware WITH (NOLOCK) ON Ware.WareNumber = Transactions.WareNumber
  INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WareGroupNumber = Ware.WareGroupNumber
  LEFT OUTER JOIN Accounts WITH (NOLOCK) ON Accounts.AccountNumber = Transactions.AccountNumber
  LEFT OUTER JOIN Products WITH (NOLOCK) ON Products.ProductNumber = Transactions.ProductNumber
  LEFT OUTER JOIN ReservationReservationXtab resX WITH (NOLOCK) ON resx.FK_ReferenceNumber = Reservations.ReferenceNumber
  LEFT OUTER JOIN Reservations sub WITH (NOLOCK) ON sub.ReferenceNumber = resx.FK_ReferenceNumberSub
    AND sub.Status < 7
  LEFT OUTER JOIN FolioRestResTableChairsXTab WITH (NOLOCK) ON FolioRestResTableChairsXTab.FolioNumber = Folios.FolioNumber
  LEFT OUTER JOIN TransactionPeriod WITH (NOLOCK) ON TransactionPeriod.FK_TransactionNumber = Transactions.TransactionNumber
  WHERE Accounts.Balance = 1
  AND Accounts.AccountType NOT IN (1, 2)
  AND CASE WHEN Folios.FolioNumber = - 1 THEN - 99 ELSE Folios.FolioNumber END IN (SELECT * FROM #FoliosCrossDate WITH (NOLOCK))
  AND (CONVERT(CHAR(8), Transactions.DateStamp, 112) <= @SystemDateStr)
  AND WareGroups.Payment NOT IN (1) --Waregroup type Payment is not included.
  AND (ISNULL(@DebugReferenceNumber, -1) = -1 OR  Folios.ReferenceNumber = @DebugReferenceNumber)
  --AND Folios.FolioNumber = 396145
  ORDER BY ISNULL(Folios.ReferenceNumber, - 1), ISNULL(Transactions.ProductWareLinkNumber, - 1), CONVERT(CHAR(8), Transactions.DateStamp, 112)
OPEN TransCur

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 12'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

DECLARE @ActualWareCount INT

FETCH NEXT FROM TransCur INTO @tmpTransdate, @ReferenceNumber, @FolioNumber, @Totalsum, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @MisType, @WarePayment, @VatValueWare, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @IsPackage, @WareGroupNumber, 
  @TransactionNumber, @Adults, @Children1, @Children2, @Pieces, @Debit, @ProductNumber, @ProductWareLinkNumber, @ResultAccountNumber, @ShowOnBillFlag, @DepartmentNumber, @GuestNumber, @FixedPrice, @DayProduct, @TransactionMoved, @TransactionDeleted, 
  @FK_ReferenceNumber, @WareType, @WareNumber, @Text, @IsRoom, @IsHall, @gtn, @TranNote, @MovedReferenceNumber, @MovedGuestNumber, @CountryNumber, @RestaurantReservationNumber, @LFromTime, @LToTime

SET @tmpProductWareLinkNumberTrans = - 1

WHILE (@@FETCH_STATUS <> - 1)
BEGIN
  IF @ShowTimeing = 1
  BEGIN
    PRINT 'Time 13'
    PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
    RAISERROR (N'', 0, 1) WITH NOWAIT
  END

  IF ISNULL(@RestaurantReservationNumber, 0) > 0
  BEGIN
    SELECT
      @ReferenceNumber = ReservationConferenceLine.ReferenceNumber,
      @SegmentNumber = CASE WHEN (ISNULL(Reservations.MarketSegment, 0) = 0) THEN ISNULL(Customer.SegmentNumber, 0) ELSE Reservations.MarketSegment END,
      @PointOfSaleNumber = CASE WHEN (ISNULL(Reservations.PointOfSale, 0) = 0) THEN ISNULL(Customer.PointOfSaleNumber, 0) ELSE Reservations.PointOfSale END,
      @PurposeCode = CASE WHEN (ISNULL(Reservations.PurposeCode, 0) = 0) THEN Customer.PurposeCodeNumber ELSE Reservations.PurposeCode END,
      @GuestType = Reservations.GuestType, @Status = TableStatus, @CampaignCode = ISNULL(Reservations.FK_CampaignCode, - 1)
    FROM ReservationConferenceLine (NOLOCK)
    INNER JOIN Reservations WITH (NOLOCK) ON Reservations.ReferenceNumber = ReservationConferenceLine.ReferenceNumber
      AND Reservations.GuestNumber = ReservationConferenceLine.GuestNo
    INNER JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.ReferenceNumber = Reservations.ReferenceNumber
      AND ReservationAddressXTab.GuestNumber = Reservations.GuestNumber
    LEFT OUTER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = ReservationAddressXTab.AddressNumber
      AND ReservationAddress.AddressType = 1
    LEFT OUTER JOIN Customer WITH (NOLOCK) ON Customer.CustomerNumber = ReservationAddress.Link
    WHERE ReservationConfLineNumber = @RestaurantReservationNumber
  END

  SET @ActualWareCount = @Pieces--Negative, when debit = 1

  IF ((ISNULL(@FK_ReferenceNumber, 0) = 0) OR @MainCourceResNotInclMIS_OrderBook = 0)
    SET @MainCourceNoValues = 0
  ELSE
    SET @MainCourceNoValues = 1

  IF @PackageSameDayAsLogi = 1
  BEGIN
    IF @ProductWareLinkNumber <= 0
      SET @TransDate = @tmpTransDate -- Do nothing
    ELSE
    BEGIN
      IF (@ProductWareLinkNumber > 0) AND (@tmpProductWareLinkNumberTrans <> @ProductWareLinkNumber)
        SET @TransDate = @tmpTransdate
    END-- Get the first date in the serie of a ProductWareLinkNumber	

    SET @tmpProductWareLinkNumberTrans = @ProductWareLinkNumber
  END
  ELSE
    SET @TransDate = @tmpTransdate

  IF ISNULL(@PointOfSaleNumber, 0) = 0
    SET @PointOfSaleNumber = @DefaultMISPointOfSale

  IF ISNULL(@SegmentNumber, 0) = 0
    SET @SegmentNumber = @DefaultMISSegment

  IF ISNULL(@GuestType, 0) = 0
    SET @GuestType = @DefaultMISGuestType

  IF ISNULL(@PurposeCode, 0) = 0
    SET @PurposeCode = @DefaultMISPurposeCode

  IF @ProductWareLinkNumber = 0
    SET @ProductWareLinkNumber = - 1

  IF ISNULL(@MisType, - 1) = - 1
    SET @MisType = 1

  SET @PackagePrice = 0

  IF (@IsPackage = 1)
  BEGIN
    SET @PackagePrice = (@TotalSum) * CONVERT(FLOAT, ((@VatValueWare / 100) + 1))
    SET @Totalsum = 0
  END

  -- Find roomtype here and if guest has stayed on the hotel
  SET @RoomTypeNumber = 0
  SET @ArrivalDate = NULL
  SET @DepartureDate = NULL
  SET @OwnerReservation = 0

  IF @IsPackage = 1 OR @WarePayment IN (2,3)  -- room/hall postings inclusive package
  BEGIN
    IF @IsRoom = 1
    BEGIN
      SET @Room_HallType = 0 --Room

      IF @TranNote <> ''
      BEGIN
        SELECT TOP 1 @RoomTypeNumber = Rooms.RoomTypeNumber
        FROM Rooms WITH (NOLOCK)
        WHERE Rooms.Number =  @TranNote
      END
      ELSE IF ISNULL(@MovedReferenceNumber, 0) > 0
      BEGIN
        SELECT TOP 1 @RoomTypeNumber = ISNULL(Rooms.RoomTypeNumber /*allocated roomtype*/, ISNULL(RoomTypes.RoomTypeNumber /*booked roomtype*/, 0))
        FROM ReservationRoomLine WITH (NOLOCK)
        INNER JOIN ReservationRoomLineXtab WITH (NOLOCK) ON ReservationRoomLineXtab.LineNumber = ReservationRoomLine.LineNumber
        INNER JOIN Reservations WITH (NOLOCK) ON Reservations.ReferenceNumber = ReservationRoomLineXTab.ReferenceNumber
          AND ReservationRoomLineXTab.GuestNumber = Reservations.GuestNumber
        LEFT OUTER JOIN Rooms WITH (NOLOCK) ON Rooms.RoomNumber = ReservationRoomLine.RoomNumber
        LEFT OUTER JOIN RoomTypes WITH (NOLOCK) ON RoomTypes.RoomTypeNumber = ReservationRoomLine.BookedTypeNumber
        WHERE Reservations.ReferenceNumber = @MovedReferenceNumber
        AND Reservations.GuestNumber = @MovedGuestNumber
      END
      ELSE
      BEGIN
        SELECT TOP 1 @RoomTypeNumber = ISNULL(Rooms.RoomTypeNumber /*allocated roomtype*/, ISNULL(RoomTypes.RoomTypeNumber /*booked roomtype*/, 0))
        FROM ReservationRoomLine WITH (NOLOCK)
        INNER JOIN ReservationRoomLineXtab WITH (NOLOCK) ON ReservationRoomLineXtab.LineNumber = ReservationRoomLine.LineNumber
        INNER JOIN Reservations WITH (NOLOCK) ON Reservations.ReferenceNumber = ReservationRoomLineXTab.ReferenceNumber
          AND ReservationRoomLineXTab.GuestNumber = Reservations.GuestNumber
        LEFT OUTER JOIN Rooms WITH (NOLOCK) ON Rooms.RoomNumber = ReservationRoomLine.RoomNumber
        LEFT OUTER JOIN RoomTypes WITH (NOLOCK) ON RoomTypes.RoomTypeNumber = ReservationRoomLine.BookedTypeNumber
        WHERE Reservations.ReferenceNumber = @ReferenceNumber
        AND Reservations.GuestNumber = @GuestNumber
      END
    END
    ELSE IF @IsHall = 1
    BEGIN
      SET @Room_HallType = 1 --Hall

      IF @TranNote <> ''
      BEGIN
        SELECT TOP 1 @RoomTypeNumber = ConferenceRoomTypeNumber
        FROM ConferenceRooms WITH (NOLOCK)
        WHERE Number = @TranNote
        AND ISNULL(Istable, 0) = 0
      END
      ELSE IF ISNULL(@MovedReferenceNumber, 0) > 0
      BEGIN
        SELECT TOP 1 @RoomTypeNumber = BookedConferenceRoomTypeNumber
        FROM ReservationConferenceLine WITH (NOLOCK)
        INNER JOIN ConferenceRoomTypes WITH (NOLOCK) ON ConferenceRoomTypes.ConferenceRoomTypeNumber = ReservationConferenceLine.BookedConferenceRoomTypeNumber
        WHERE ReservationConferenceLine.ReferenceNumber = @MovedReferenceNumber
        AND ReservationConferenceLine.GuestNo = @MovedGuestNumber
        AND ArrivalDate = @tmpTransdate
        AND ProductNumber = @ProductNumber

        --Moved from another date???
        IF ISNULL(@RoomTypeNumber, 0) = 0  -- if hall is charged per guest, then transaction is related to guest > 0, but halls is on guest = 0
        BEGIN
          SELECT TOP 1 @RoomTypeNumber = BookedConferenceRoomTypeNumber
          FROM ReservationConferenceLine WITH (NOLOCK)
          INNER JOIN ConferenceRoomTypes WITH (NOLOCK) ON ConferenceRoomTypes.ConferenceRoomTypeNumber = ReservationConferenceLine.BookedConferenceRoomTypeNumber
          WHERE ReservationConferenceLine.ReferenceNumber = @MovedReferenceNumber
          AND ReservationConferenceLine.GuestNo = @MovedGuestNumber
          AND ProductNumber = @ProductNumber
        END
      END
      ELSE
      BEGIN
        SELECT TOP 1 @RoomTypeNumber = BookedConferenceRoomTypeNumber
        FROM ReservationConferenceLine WITH (NOLOCK)
        INNER JOIN ConferenceRoomTypes WITH (NOLOCK) ON ConferenceRoomTypes.ConferenceRoomTypeNumber = ReservationConferenceLine.BookedConferenceRoomTypeNumber
        WHERE ReservationConferenceLine.ReferenceNumber = @ReferenceNumber
        AND ReservationConferenceLine.GuestNo = @GuestNumber
        AND ArrivalDate = @tmpTransdate
        AND ProductNumber = @ProductNumber

        IF ISNULL(@RoomTypeNumber, 0) = 0  -- if hall is charged per guest, then transaction is related to guest > 0, but halls is on guest = 0
        BEGIN
          SELECT TOP 1 @RoomTypeNumber = BookedConferenceRoomTypeNumber
          FROM ReservationConferenceLine WITH (NOLOCK)
          INNER JOIN ConferenceRoomTypes WITH (NOLOCK) ON ConferenceRoomTypes.ConferenceRoomTypeNumber = ReservationConferenceLine.BookedConferenceRoomTypeNumber
          WHERE ReservationConferenceLine.ReferenceNumber = @ReferenceNumber
          AND ReservationConferenceLine.GuestNo = 0
          AND ArrivalDate = @tmpTransdate
          AND ProductNumber = @ProductNumber
        END

        IF ISNULL(@RoomTypeNumber, 0) = 0  -- Hall is on multiple dates
        BEGIN
          SELECT TOP 1 @RoomTypeNumber = BookedConferenceRoomTypeNumber
          FROM ReservationConferenceLine WITH (NOLOCK)
          INNER JOIN ConferenceRoomTypes WITH (NOLOCK) ON ConferenceRoomTypes.ConferenceRoomTypeNumber = ReservationConferenceLine.BookedConferenceRoomTypeNumber
          WHERE ReservationConferenceLine.ReferenceNumber = @ReferenceNumber
          AND ReservationConferenceLine.GuestNo = 0
          AND ProductNumber = @ProductNumber
        END
      END
    END
  END
  ELSE
    SET @Room_HallType = 3 --no room, no hall

  SET @Adults = 0
  SET @Children1 = 0
  SET @Children2 = 0
  SET @Pieces = 0

  IF @MisType = 1  -- Other
    SET @ValueType = 5 
  ELSE IF @MisType = 2 -- Restaurant
    SET @ValueType = 4

  SELECT TOP 1 @RelatedMisType = WareGroups.WareType, @RelatedWarePayment = WareGroups.Payment
  FROM Transactions t1 WITH (NOLOCK)
  INNER JOIN TransactionTransactionXtab WITH (NOLOCK) ON TransactionTransactionXtab.FK_TransactionNumber2 = t1.TransactionNumber
  INNER JOIN Transactions t2 ON t2.TransactionNumber = TransactionTransactionXtab.FK_TransactionNumber1
  INNER JOIN Ware WITH (NOLOCK) ON Ware.WareNumber = t2.WareNumber
  INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WareGroupNumber = Ware.WareGroupNumber
  WHERE t1.GlobalTransactionNumber = @gtn
  AND t1.ShowOnBillFlag = 1

  IF (@WarePayment IN (2,7)) OR -- AutoRoom or ManualRooms. Must not follow any mistype. Allways include in mis.
    (@ChargeDiscountAsProduct = 1 AND @WarePayment = 5 AND @WareType = 19 AND @RelatedWarePayment IN (2,7)) -- Discount as product
  BEGIN
    SET @ValueType = 1
    GOTO Store
  END
  ELSE
  BEGIN
    IF (@WarePayment IN (3,8)) OR -- AutoHall or ManualHalls. Must not follow any mistype. Allways include in mis.
      (@ChargeDiscountAsProduct = 1 AND @WarePayment = 5 AND @WareType = 19 AND @RelatedWarePayment IN (3,4)) -- Discount as product
    BEGIN
      IF (@ProductNumber <= 0)
        SET @FixedPrice = 0

      IF @FixedPrice = 0
        SET @ValueType = 3
      ELSE
        SET @ValueType = 2

      GOTO Store
    END
  END

  IF (@ChargeDiscountAsProduct = 1 AND @WarePayment = 5 AND @WareType = 19 AND @RelatedMisType IN (1,2)) OR -- Discount as product
    @MisType IN (1,2)
  BEGIN
    GOTO Store
  END

  GOTO Skip

  Store:

  IF (@IsPackage = 1) -- Packages must follow the Rooms/Daymeeting/Halls category.
  BEGIN
    IF (@DayProduct = 0)
      SET @ValueType = 1
    ELSE
    BEGIN
      IF (@FixedPrice = 0)
        SET @ValueType = 3
      ELSE
        SET @ValueType = 2
    END
  END

  IF (@ShowOnBillFlag = 0)
  BEGIN
    SET @Totalsum = (@Totalsum) * CONVERT(FLOAT, ((@VatValueWare / 100) + 1))

    IF (@Debit = 1)
      SET @Pieces = @Pieces * - 1 --Now positive

    IF (@TransDate < @SystemDateStr)
    BEGIN
      IF @MainCourceNoValues = 1
      BEGIN
        IF @ShowPrint = 1
          PRINT 'MAIN Actual ' + CONVERT(VARCHAR, @Referencenumber) + ', ' + CONVERT(VARCHAR, @Adults) + ', ' + CONVERT(VARCHAR, @Totalsum)

        SET @Adults = 0
        SET @Children1 = 0
        SET @Children2 = 0
        SET @Pieces = 0
        SET @Totalsum = 0
        SET @PackagePrice = 0
      END

      -- Actual	
      INSERT INTO MISTABLE (DateStamp, ReferenceNumber, FolioNumber, SegmentNumber, PointOfSaleNumber, FK_GuestTypeNumber, FK_PurposeCodeNumber, RoomTypeNumber, BookedAdult, BookedChildren1, BookedChildren2, BookedNumberOfRooms, BookedPrice, BookedVatOfPrice, BookedPackage, BookedVatOfPackage, 
        ActualAdult, ActualChildren1, ActualChildren2, ActualNumberOfRooms, ActualPrice, ActualVatOfPrice, ActualPackage, ActualVatOfPackage, ValueType, HotelCustomerNumber, ReservationStatus, CampaignCode, ProjectCode, StaffID, AccountNumber, MisData, DepartmentNumber, 
        ProductWareLinkNumber, IsPackage, GuestNumber, Room_HallType, CorrectionMoved, CorrectionDeleted, TEXT, WareGroupNumber, OwnerReservation, ProductNumber, WareType, WareNumber, BookedWareCount, ActualWareCount, FK_CountryNumber, FromTime, ToTime)
      VALUES (@TransDate, @ReferenceNumber, @FolioNumber, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, ISNULL(@RoomTypeNumber, 0), 0, 0, 0, 0, 0, 0, 0, 0, 
        @Adults, @Children1, @Children2, @Pieces, @Totalsum, (@Totalsum * ((1 - (1 / CONVERT(FLOAT, ((@VatValueWare / 100) + 1)))))), @PackagePrice, @PackagePrice * ((1 - (1 / CONVERT(FLOAT, ((@VatValueWare / 100) + 1))))), @ValueType, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @ResultAccountNumber, 1, @DepartmentNumber, 
        @ProductWareLinkNumber, @IsPackage, @GuestNumber, @Room_HallType, @TransactionMoved, @TransactionDeleted, @Text, @WareGroupNumber, @OwnerReservation, @ProductNumber, @WareType, @WareNumber, 0, @ActualWareCount, @CountryNumber, @LFromTime, @LToTime)
    END
  END

  Skip:

  FETCH NEXT FROM TransCur INTO @tmpTransdate, @ReferenceNumber, @FolioNumber, @Totalsum, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @MisType, @WarePayment, @VatValueWare, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @IsPackage, @WareGroupNumber,
    @TransactionNumber, @Adults, @Children1, @Children2, @Pieces, @Debit, @ProductNumber, @ProductWareLinkNumber, @ResultAccountNumber, @ShowOnBillFlag, @DepartmentNumber, @GuestNumber, @FixedPrice, @DayProduct, @TransactionMoved, @TransactionDeleted, @FK_ReferenceNumber, 
    @WareType, @WareNumber, @Text, @IsRoom, @IsHall, @gtn, @TranNote, @MovedReferenceNumber, @MovedGuestNumber, @CountryNumber, @RestaurantReservationNumber, @LFromTime, @LToTime
END--while

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 14'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

CLOSE TransCur
DEALLOCATE TransCur

IF @ShowPrint = 1
BEGIN
  PRINT '**** END Normal MIS calculation'
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

DROP TABLE #ReferenceExtrasTable
DROP TABLE #PacketWareTable

EXEC MisUpdateProductWareLinkNumbers-- Handles ProductWareLinkNumber = -100 and -200

DELETE FROM MISTABLEPackSum

INSERT INTO MISTABLEPackSum (ProductWareLinkNumber, PackageSum, PackageVatOfSum)
SELECT ProductWareLinkNumber, PackageSum, PackageVatOfSum
FROM MISPackagesSum()

IF @NightAuditRunning = 1
BEGIN
  UPDATE Hotelsetup SET KeyValue = @SystemDateStr WHERE Searchkey = 'LastMISUpdate'

  IF @CalcOnlyChangedReservations <> 1 --Called from NightAudit with 0, when MISTotalCalcNeeded = 1
    UPDATE Hotelsetup  SET KeyValue = 0 WHERE SearchKey = 'MISTotalCalcNeeded'
END

IF @NightAuditRunning = 1 OR @CalcOnlyChangedReservations = 1
BEGIN
  UPDATE Hotelsetup
  SET KeyValue = CONVERT(CHAR(23), GETDATE(), 126) --yyyy-mm-ddThh:mi:ss.mmm (no spaces)
  WHERE Searchkey = 'LastMISChangedUpdate'
END

DECLARE @Faktor FLOAT
DECLARE @BookedPrice MONEY
DECLARE @BookedVatOfPrice MONEY
DECLARE @PackageSum MONEY
DECLARE @PackageVatOfSum MONEY
DECLARE @BookedAdult INT
DECLARE @BookedChildren1 INT
DECLARE @BookedChildren2 INT
DECLARE @BookedPackage MONEY
DECLARE @BookedVatOfPackage MONEY
DECLARE @ActualAdult INT
DECLARE @ActualChildren1 INT
DECLARE @ActualChildren2 INT
DECLARE @ActualPackage MONEY
DECLARE @ActualVatOfPackage MONEY
DECLARE @ActualNumberOfRooms INT
DECLARE @ActualPrice MONEY
DECLARE @ActualVatOfPrice MONEY
DECLARE @ReadOnly BIT
DECLARE @ReservationStatus INT
DECLARE @AccountNumber INT
DECLARE @CorrectionMoved BIT
DECLARE @CorrectionDeleted BIT

IF @ShowPrint = 1
BEGIN
  PRINT 'Calc of real vat of Product price. MisTable (VatOfPriceCur)'
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 15'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

DECLARE VatOfPriceCur CURSOR STATIC FOR
  SELECT Room_HallType, MISTABLE.ReferenceNumber, GuestNumber, FolioNumber, MISTABLE.DateStamp, SegmentNumber, PointOfSaleNumber, FK_GuestTypeNumber, FK_PurposeCodeNumber, RoomTypeNumber, 
  BookedAdult, BookedChildren1, BookedChildren2, BookedNumberOfRooms, BookedPrice, BookedVatOfPrice, BookedPackage, BookedVatOfPackage, 
  ActualAdult, ActualChildren1, ActualChildren2, ActualNumberOfRooms, ActualPrice, ActualVatOfPrice, ActualPackage, ActualVatOfPackage, 
  ValueType, HotelCustomerNumber, ReadOnly, ReservationStatus, CampaignCode, ProjectCode, StaffID, CorrectionMoved, CorrectionDeleted, WareGroupNumber, AccountNumber, DepartmentNumber, MISTABLE.ProductWareLinkNumber, IsPackage, Text,
  OwnerReservation, ProductNumber, ISNULL(MISTABLEPackSum.PackageSum, 0), ISNULL(MISTABLEPackSum.PackageVatOfSum, 0), ISNULL(WareType, 99) AS WareType, ISNULL(WareNumber, 0) AS WareNumber, ISNULL(ActualWareCount, 0) AS ActualWareCount, ISNULL(BookedWareCount, 0) AS BookedWareCount,
  FK_CountryNumber, FromTime, ToTime
  FROM MISTABLE WITH (NOLOCK)
  LEFT JOIN MISTABLEPackSum WITH (NOLOCK) ON MISTABLEPackSum.ProductWareLinkNumber = MISTABLE.ProductWareLinkNumber
  WHERE MISTABLE.ProductWareLinkNumber >= 0
  AND MISTABLE.IsPackage = 0
  AND MISTABLE.DateStamp >= @SystemDateStr
  AND WareType NOT IN (10, 11, 12, 13, 14, 15, 16, 17, 18) --Provision
  AND (@CountResToRecalc = 0 OR Referencenumber IN (SELECT * FROM #ResToRecalc))
OPEN VatOfPriceCur

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 16'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END

DELETE
FROM MISTABLE
WHERE MISTABLE.ProductWareLinkNumber >= 0
  AND MISTABLE.IsPackage = 0
  AND MISTABLE.DateStamp >= @SystemDateStr
  AND WareType NOT IN (10, 11, 12, 13, 14, 15, 16, 17, 18) --Provision
  AND (@CountResToRecalc = 0 OR Referencenumber IN (SELECT * FROM #ResToRecalc))

DECLARE @ActWareCount INT
DECLARE @BookWareCount INT

FETCH NEXT FROM VatOfPriceCur INTO @Room_HallType, @ReferenceNumber, @GuestNumber, @FolioNumber, @DateStamp, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @RoomTypeNumber, 
  @BookedAdult, @BookedChildren1, @BookedChildren2, @BookedNumberOfRooms, @BookedPrice, @BookedVatOfPrice, @BookedPackage, @BookedVatOfPackage, 
  @ActualAdult, @ActualChildren1, @ActualChildren2, @ActualNumberOfRooms, @ActualPrice, @ActualVatOfPrice, @ActualPackage, @ActualVatOfPackage, 
  @ValueType, @HotelCustomerNumber, @ReadOnly, @ReservationStatus, @CampaignCode, @ProjectCode, @StaffID, @CorrectionMoved, @CorrectionDeleted, @WareGroupNumber, @ResultAccountNumber, @DepartmentNumber, @ProductWareLinkNumber, @IsPackage, @Text, 
  @OwnerReservation, @ProductNumber, @PackageSum, @PackageVatOfSum, @WareType, @WareNumber, @ActWareCount, @BookWareCount, @CountryNumber, @LFromTime, @LToTime

WHILE (@@FETCH_STATUS <> - 1)
BEGIN
  IF @ShowTimeing = 1
  BEGIN
    PRINT 'Time 17'
    PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
    RAISERROR (N'', 0, 1) WITH NOWAIT
  END

  SET @Faktor = 0

  IF (@BookedPrice <> 0)
  BEGIN
    SET @Faktor = CONVERT(FLOAT, @BookedVatOfPrice / @BookedPrice)
    SET @BookedVatOfPrice = ((@BookedPrice - @PackageSum) * @Faktor) + @PackageVatOfSum
  END
  ELSE
    SET @BookedVatOfPrice = 0

  INSERT INTO MISTABLE (Room_HallType, ReferenceNumber, GuestNumber, FolioNumber, DateStamp, SegmentNumber, PointOfSaleNumber, FK_GuestTypeNumber, FK_PurposeCodeNumber, RoomTypeNumber, 
    BookedAdult, BookedChildren1, BookedChildren2, BookedNumberOfRooms, BookedPrice, BookedVatOfPrice, BookedPackage, BookedVatOfPackage, ActualAdult, ActualChildren1, ActualChildren2, ActualNumberOfRooms, ActualPrice, ActualVatOfPrice, ActualPackage, ActualVatOfPackage, 
    ValueType, HotelCustomerNumber, ReadOnly, ReservationStatus, CampaignCode, ProjectCode, StaffID, CorrectionMoved, CorrectionDeleted, WareGroupNumber, AccountNumber, DepartmentNumber, ProductWareLinkNumber, IsPackage, TEXT, 
    OwnerReservation, ProductNumber, WareType, WareNumber, ActualWareCount, BookedWareCount, FK_CountryNumber, FromTime, ToTime)
  VALUES (@Room_HallType, @ReferenceNumber, @GuestNumber, @FolioNumber, @DateStamp, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, ISNULL(@RoomTypeNumber, 0), --2021-04-13, sg: Tried to insert NULL in NightAudit (not in manuel execution!)
    @BookedAdult, @BookedChildren1, @BookedChildren2, @BookedNumberOfRooms, @BookedPrice, @BookedVatOfPrice, @BookedPackage, @BookedVatOfPackage, @ActualAdult, @ActualChildren1, @ActualChildren2, @ActualNumberOfRooms, @ActualPrice, @ActualVatOfPrice, @ActualPackage, @ActualVatOfPackage, 
    @ValueType, @HotelCustomerNumber, @ReadOnly, @ReservationStatus, @CampaignCode, @ProjectCode, @StaffID, @CorrectionMoved, @CorrectionDeleted, @WareGroupNumber, @ResultAccountNumber, @DepartmentNumber, @ProductWareLinkNumber, @IsPackage, @Text, 
    @OwnerReservation, @ProductNumber, @WareType, @WareNumber, @ActWareCount, @BookWareCount, @CountryNumber, @LFromTime, @LToTime)

  FETCH NEXT FROM VatOfPriceCur INTO @Room_HallType, @ReferenceNumber, @GuestNumber, @FolioNumber, @DateStamp, @SegmentNumber, @PointOfSaleNumber, @GuestType, @PurposeCode, @RoomTypeNumber, 
    @BookedAdult, @BookedChildren1, @BookedChildren2, @BookedNumberOfRooms, @BookedPrice, @BookedVatOfPrice, @BookedPackage, @BookedVatOfPackage, 
    @ActualAdult, @ActualChildren1, @ActualChildren2, @ActualNumberOfRooms, @ActualPrice, @ActualVatOfPrice, @ActualPackage, @ActualVatOfPackage, 
    @ValueType, @HotelCustomerNumber, @ReadOnly, @ReservationStatus, @CampaignCode, @ProjectCode, @StaffID, @CorrectionMoved, @CorrectionDeleted, @WareGroupNumber, @ResultAccountNumber, @DepartmentNumber, @ProductWareLinkNumber, @IsPackage, @Text, 
    @OwnerReservation, @ProductNumber, @PackageSum, @PackageVatOfSum, @WareType, @WareNumber, @ActWareCount, @BookWareCount, @CountryNumber, @LFromTime, @LToTime
END

CLOSE VatOfPriceCur
DEALLOCATE VatOfPriceCur

DROP TABLE #ReservationsCrossDate
DROP TABLE #FoliosCrossDate
DROP TABLE #ResToRecalc
DROP TABLE #PacketInfo

DECLARE @StartDate DATETIME
SET @StartDate = CONVERT(DATETIME, @FormatedStartDate)
EXEC GenerateMISTotals @StartDate

IF @MISAllotmentEnable = 1
BEGIN
  IF @ShowPrint = 1
    PRINT 'MISGenerateAllotment start'
  EXEC MISGenerateAllotment
  IF @ShowPrint = 1
    PRINT 'MISGenerateAllotment end'
END

UPDATE HotelSetup SET KeyValue = 0 WHERE Searchkey = 'MISCalcRunning'

IF @ShowTimeing = 1
BEGIN
  PRINT 'Time 18'
  PRINT CONVERT(VARCHAR(25), GETDATE(), 14)
  RAISERROR (N'', 0, 1) WITH NOWAIT
END
