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;

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

   Changes:
    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 INTEGER;
     DECLARE @PointOfSaleNumber INTEGER;
     DECLARE @RoomTypeNumber INTEGER;
     DECLARE @HallTypeNumber INTEGER;
     DECLARE @BookedNumberOfRooms INTEGER; 
     DECLARE @Adults INTEGER;
     DECLARE @Children1 INTEGER;
     DECLARE @Children2 INTEGER;
     DECLARE @Pieces INTEGER;
     DECLARE @Debit BIT;
     DECLARE @PaysAdults INTEGER;
     DECLARE @PaysChildren1 INTEGER;
     DECLARE @PaysChildren2 INTEGER;
     DECLARE @TotalAdults INTEGER;
     DECLARE @TotalChildren1 INTEGER;
     DECLARE @TotalChildren2 INTEGER;
     DECLARE @CurrentDateStr CHAR(8);
     DECLARE @TempCurrentDateStr CHAR(8);
     DECLARE @CurrentDate DATETIME;
     DECLARE @SystemDateStr CHAR(8);
     DECLARE @FormatedStartDate CHAR(8);
     DECLARE @SystemDate DATETIME;
     DECLARE @AllocatedTypeNumber INTEGER;
     DECLARE @Room_HallType TINYINT;
     -- 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 @WarePrice REAL;
     DECLARE @ResultAccountNumber INT;
     DECLARE @ResultAccountNumber_ForDiscount INT;
     DECLARE @ResultAccountPackage INT;
     DECLARE @ResultAccountNumberExtras INT;
     DECLARE @ResultAccountNumberExtras_ForDiscount INT;
     DECLARE @DepartmentNumber SMALLINT;
     DECLARE @DepartmentNumberPackage SMALLINT;
     DECLARE @DepartmentNumberExtras SMALLINT;
     DECLARE @GlobalTransactionNumber INT;
     DECLARE @TransactionNumber INT;
     DECLARE @VatValueWare FLOAT;
     DECLARE @VatByPacketValue FLOAT;
     DECLARE @PackagePrice FLOAT;
     DECLARE @PackagePriceVatOf FLOAT;
     DECLARE @PackagePriceSum FLOAT;
     DECLARE @PackagePriceVatOfSum FLOAT;
     DECLARE @PacketWarePrice FLOAT;
     DECLARE @VatOfPacketWarePrice FLOAT;
     DECLARE @PacketNumber INT;
     DECLARE @PacketNumberReservation INT;
     DECLARE @TotalPriceDay MONEY;
     DECLARE @TotalPriceDay_ForDiscount MONEY;
     DECLARE @TotalPriceDay_ForDiscountVat 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 @GuestNumberExtras INT;
     DECLARE @PrevLineNumber INTEGER;
     DECLARE @PrevReferenceNumber INT;
     DECLARE @PrevGuestNumber INTEGER;
     DECLARE @SmallestArrivalDate CHAR(8);
     DECLARE @BiggestDepartureDate CHAR(8);
     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;
     DECLARE @ProductStartDate DATETIME;
     DECLARE @ProductEndDate DATETIME;
     DECLARE @TmpProductStartDate DATETIME;
     DECLARE @TmpProductEndDate DATETIME;
     DECLARE @TableCount SMALLINT;
     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 @WareNumberExtras 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;
     DECLARE @ValueTypeExtra TINYINT;
     DECLARE @MisData BIT;
     DECLARE @Arr24 CHAR(5);
     DECLARE @ArrArrivalTime CHAR(5);
     DECLARE @ArrDepartureTime CHAR(5);
     DECLARE @OldSegmentNumber INT;
     DECLARE @TotalExtra MONEY;
     DECLARE @TotalExtra_ForDiscount MONEY;
     DECLARE @TotalExtra_ForDiscountVat MONEY;
     DECLARE @VATOfTotalExtra MONEY;
     DECLARE @DefaultMISPointOfSale INT;
     DECLARE @DefaultMISSegment INT;
     DECLARE @NameListSetting TINYINT;
     DECLARE @NameListSettingHotelSetup TINYINT;
     DECLARE @MisType INT;
     DECLARE @WareType INT;
     DECLARE @WarePayment SMALLINT;
     DECLARE @Correction BIT; --Anvendes ikke
     DECLARE @ManuelUser BIT;
     DECLARE @Totalsum MONEY;
     DECLARE @TotalsumVat MONEY;
     DECLARE @TransDate CHAR(8);
     DECLARE @tmpTransdate CHAR(8);
     DECLARE @OnePersonPaysForAll BIT;
     DECLARE @IncludeTentative BIT;
     DECLARE @MinArrivalDate CHAR(8);
     DECLARE @MaxDepartureDate CHAR(8);
     DECLARE @IncludeProvisionbackward BIT;
     DECLARE @IncludeDayroomsInSoldRooms BIT;
     DECLARE @DayroomsLaterThanTime CHAR(5);
     DECLARE @ConflineOnMainRes BIT;
     DECLARE @NightAuditRunning BIT;
     DECLARE @MISCalcRunning BIT;
     DECLARE @OneDayBack BIT;
     DECLARE @HotelCustomerNumber INT;
     DECLARE @CentralBookingType SMALLINT;
     DECLARE @LastMISUpdate DATETIME;        --Updated by nightaudit
     DECLARE @LastMISChangedUpdate DATETIME; --Updated changed reservations
     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 INT;
     DECLARE @ProductWareLinkNumberMis INT;
     DECLARE @ProductWareLinkNumberTrans INT;
     DECLARE @PackageStored BIT;
     DECLARE @tmpProductWareLinkNumberTrans INT;
     DECLARE @tmpProductWareLinkNumberMis INT;
     DECLARE @ShowOnBillFlag BIT;
     DECLARE @ForceLodgingChargeOfZeroPrice BIT;
     DECLARE @InhouseDebitor BIT;
     DECLARE @UserTypeNumber SMALLINT;
     DECLARE @TransactionMoved BIT;
     DECLARE @TransactionDeleted BIT;
     DECLARE @Text VARCHAR(100);
     DECLARE @OwnerReservation BIT;
     DECLARE @OrderBookBudgetCalcDiscount BIT;
     DECLARE @CalcDiscount BIT;
     DECLARE @DiscountWareNumber INT;
     DECLARE @DiscountAsNettoPrice BIT;
     DECLARE @ChargeDiscountAsProduct BIT;
     DECLARE @DiscountResultAccountNumber INT;
     DECLARE @DiscountVatValueWare FLOAT;
     DECLARE @SplitBillNumber INT;
     DECLARE @RoomTypeHotelNumber INT;
     DECLARE @FK_ReferenceNumber INT;
	 DECLARE @IsTableBooking int;
     --DECLARE @DiscountSpec BIT
     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
	
	--MISCalcRunning
     SELECT @MISCalcRunning = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'MISCalcRunning';
	 SET @MISCalcRunning = ISNULL(@MISCalcRunning, 0)
     If @MISCalcRunning = 1
	 Begin
	   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
    BEGIN
      INSERT INTO HotelSetup (SearchKey, KeyValue) VALUES ('MISCalcRunning', 1);
    END ELSE
	BEGIN
	  UPDATE HotelSetup set KeyValue = 1 Where  Searchkey = 'MISCalcRunning';
	END;

     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] INT NULL,
      [ProductNumber]         INT NULL,
	    [BookedWareCount]       INT 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
     BEGIN
       SET @NightAuditRunning = 0;
     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')
       
       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 = ''
     Begin
       Set @DatesForLog = 'NORMAL'
     End Else
     Begin
       Set @DatesForLog = SUBSTRING(@CalcMISFromDate, 5, 4);
       If @CalcMISToDate <> ''
       Begin
         Set @DatesForLog += SUBSTRING(@CalcMISToDate, 5, 4);
       End
     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';
     IF ISNULL(@ChargeDiscountAsProduct, 0) = 0
     BEGIN
       SET @ChargeDiscountAsProduct = 0;
     END;
     SELECT @DiscountWareNumber = DiscountWareNumber,
            @DiscountResultAccountNumber = DiscountResultAccountNumber,
            @DiscountVatValueWare = DiscountVatValueWare
     FROM dbo.GetDiscountWareInfo();

     -- For discount calculation end
     SELECT @CentralBookingType = CONVERT( INTEGER, ISNULL(KeyValue, 0))
     FROM HotelSetup WITH (NOLOCK)
     WHERE searchkey LIKE '%CentralBookingType%';
     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
     BEGIN
       SET @IncludeDayroomsInSoldRooms = 0
     END;
     IF((@DayroomsLaterThanTime = '')
        OR (@DayroomsLaterThanTime IS NULL))
     BEGIN
       SET @DayroomsLaterThanTime = '13:00'
     END; -- hvis empty skal sættes til 13:00   

     SELECT @OnePersonPaysForAll = CONVERT( BIT, KeyValue)
     FROM HotelSetUp WITH (NOLOCK)
     WHERE SearchKey = 'OnePersonPaysForAll';
     IF ISNULL(@OnePersonPaysForAll, 0) = 0
     BEGIN
       SET @OnePersonPaysForAll = 0
     END;
     SELECT @NameListSettingHotelSetup = CONVERT( INTEGER, KeyValue)
     FROM Hotelsetup WITH (NOLOCK)
     WHERE Searchkey = 'NameListReservationPerPerson';
     SELECT @IncludeTentative = CONVERT( BIT, KeyValue)
     FROM Hotelsetup WITH (NOLOCK)
     WHERE Searchkey = 'IncludeTentativeInMISAndOrderbook';
     IF ISNULL(@IncludeTentative, 0) = 0
     BEGIN
       SET @IncludeTentative = 0
     END;
     SELECT @PackageSameDayAsLogi = CONVERT( BIT, KeyValue)
     FROM HotelSetup WITH (NOLOCK)
     WHERE SearchKey = 'PackageSameDayAsLogi';
     SET @PackageSameDayAsLogi = ISNULL(@PackageSameDayAsLogi, 0);
     SELECT @ForceLodgingChargeOfZeroPrice = CONVERT( BIT, KeyValue)
     FROM HotelSetup WITH (NOLOCK)
     WHERE SearchKey = 'ForceLodgingChargeOfZeroPrice';
     SET @ForceLodgingChargeOfZeroPrice = ISNULL(@ForceLodgingChargeOfZeroPrice, 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

     SET @FirstFetch = 1;
     SET @TableCount = 0; -- 0 = Roomline og 1=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
     BEGIN
       SET @OldSegmentNumber = 0
     END;
     
     --Find AddOn Ware
     --Declare @AddonBalanceAccountNumber int
     Declare @AddonResultAccountNumber int
     Declare @AddonWareText varchar(100)
     Declare @AddonWareType int
     Declare @AddonWareNumber int

     Select
       --@AddonBalanceAccountNumber = Ware.BalanceAccountNumber,
       @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

     --print '@AddonResultAccountNumber=' + convert(varchar, @AddonResultAccountNumber)
     --print '@AddonWareText=' + convert(varchar, @AddonWareText ) + ', @AddonWareType=' + convert(varchar, @AddonWareType) + ', @AddonWareNumber=' + convert(varchar, @AddonWareNumber)


     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
      BEGIN
	      SET @StartD = ISNULL(CONVERT(DATETIME, @LastMISUpdate) - 1, @SystemDate);
      END
      ELSE BEGIN
	      SET @StartD = ISNULL(CONVERT(DATETIME, @LastMISUpdate) - 1, @SystemDate - 1);
      END; -- decrease FormatedStartDate with one or more for getting latest posted transaction. This is important specially when updating from nightaudit.
	    SET @CalcMISToDate = '21001231';
	    SET @FormatedStartDate = CONVERT(CHAR(8), @StartD, 112);
    END ELSE
    BEGIN
      SET @FormatedStartDate = @CalcMISFromDate;
      If IsNull(@CalcMISToDate, '') = '' --default
	    BEGIN
	      SET @CalcMISToDate =  '21001231';
      END
    END;
    IF @CalcSystemDateOnly = 1
    BEGIN
      SET @FormatedStartDate = @SystemDateStr
	    SET @CalcMISToDate = @SystemDateStr
    END;
	  print '@FormatedStartDate = ' + @FormatedStartDate + ' @CalcMISToDate = ' + @CalcMISToDate
    RAISERROR(N'', 0, 1) WITH NOWAIT

     --Genberegning af rettede reservationer
     CREATE TABLE #ResToRecalc(ReferenceNumber INT);
     IF @DebugReferenceNumber <> -1
     BEGIN
       INSERT INTO #ResToRecalc(ReferenceNumber)
     VALUES(@DebugReferenceNumber);
     END;
     IF @CalcOnlyChangedReservations = 1
     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;

     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;
     
	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 @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;

	--SELECT '#ReservationsCrossDate', ReferenceNumber from #ReservationsCrossDate order by ReferenceNumber

     -- 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);

	--SELECT '#FoliosCrossDate', FolioNumber from #FoliosCrossDate order by FolioNumber

     --Delete data 
	-- #ReservationsCrossDate is empty when @CalcSystemDateOnly = 1
     --If @CalcMISFromDate = ''
	--Begin
	Declare @CancelDeleteDate Char(8);
	IF @NightAuditRunning = 1
	Begin
	  Set @CancelDeleteDate =  Convert(Char(8),  DateAdd(DAY, -1, Convert(Date, @FormatedStartDate)), 112)
	End Else
	Begin
      Set @CancelDeleteDate = @FormatedStartDate;
	End
	
--	print '@CancelDeleteDate=' + @CancelDeleteDate + ', @FormatedStartDate=' + @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)
    )
     
     --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
     BEGIN
       SET @AddonIfPriceOverwritten = 0
     END;
     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 @IncludeProvisionbackward = CONVERT( BIT, KeyValue)
     FROM HotelSetUp WITH (NOLOCK)
     WHERE SearchKey = 'IncludeProvisionbackwardInMIS';
     IF ISNULL(@IncludeProvisionbackward, 0) = 0
     BEGIN
       SET @IncludeProvisionbackward = 0
     END;
     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
     BEGIN
       SET @ProductWareLinkNumber = @ProductWareLinkNumberMis + 1000000 -- 100000 -> 1000000 
     END; -- 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
	BEGIN
	  SET @ProductWareLinkNumber = 500000
	END

print '@ProductWareLinkNumber=' + convert(varchar, @ProductWareLinkNumber) + ', @ProductWareLinkNumberMis=' +convert(varchar, @ProductWareLinkNumberMis) + ', @ProductWareLinkNumberTrans=' +convert(varchar, @ProductWareLinkNumberTrans)
RAISERROR(N'', 0, 1) WITH NOWAIT

     SET @ProductWareLinkNumber = ISNULL(@ProductWareLinkNumber, 1);
     CREATE TABLE #ReferenceExtrasTable
     (ReferenceNumber INT NOT NULL,
      CurrentDate     CHAR(8)
     );
     IF @CalcSystemDateOnly = 0
     BEGIN
    WHILE(@TableCount <= @DayProduct)
    BEGIN
        SET @TableCount = @TableCount + 1;
        IF @TableCount = 1 -- Roomline   
        BEGIN
        SET @ValueType = 1;
        SET @PrevLineNumber = 0;
        SET @GenerateDayProduct = 0;
        SET @PrevGuestNumber = 0;
        DECLARE ReservationCur CURSOR FAST_FORWARD READ_ONLY
        FOR
            SELECT DISTINCT -- Fjerner dubletter (linenumber) 
                    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 As RoomTypeNumber, 
                    RESERVATIONROOMLINE.RoomNumber,
                    RESERVATIONROOMLINEXTAB.ReferenceNumber AS ReferenceNumber,
                    RESERVATIONROOMLINEXTAB.GuestNumber AS GuestNumber,
                    ISNULL(RESERVATIONS.STATUS, 0) as Status,
                    RESERVATIONS.MARKETSEGMENT,
                    RESERVATIONS.POINTOFSALE,
                    RESERVATIONROOMLINE.ArrivalDate AS ArrivalDate,
                    RESERVATIONROOMLINE.DepartureDate AS 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, -- Plenum 
                    isnull(RESERVATIONS.FK_CampaignCode, -1) AS Campaign,
                    ISNULL(RESERVATIONMAIN.FK_ProjectCode, -1) AS Project,
                    ISNULL(RESERVATIONMAIN.StaffID, -1) AS StaffID,
                    CASE WHEN((Rooms.CustomerNumber IS NOT NULL
                                AND RESERVATIONADDRESS.LINK IS NOT NULL)
                            AND Rooms.CustomerNumber = RESERVATIONADDRESS.LINK) THEN 1
                        ELSE 0
                    END AS OwnerReservation,
                    RESERVATIONS.SplitBill,
		            RoomTypes.HotelNumber as roomTypeHotelNumber,
		            FK_ReferenceNumber
            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 RESERVATIONS.STATUS IN(0, 1, 2, 3, 5, 6, 7, 8))
                OR (@IncludeTentative = 1
                    AND RESERVATIONS.STATUS IN(0, 1, 2, 3, 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 dbo.Rooms WITH (NOLOCK) ON ReservationRoomLine.RoomNumber = Rooms.RoomNumber
                LEFT OUTER JOIN dbo.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 @CentralBookingType = 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
            SELECT DISTINCT -- Fjerner dubletter (linenumber)
                    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 As RoomTypeNumber, 
                    RESERVATIONROOMLINE.RoomNumber,
                    RESERVATIONS.ReferenceNumber AS ReferenceNumber,
                    RESERVATIONS.GuestNumber AS GuestNumber,
                    ISNULL(RESERVATIONS.STATUS, 0) as Status,
                    RESERVATIONS.MARKETSEGMENT,
                    RESERVATIONS.POINTOFSALE,
                    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) AS Campaign,
                    ISNULL(RESERVATIONMAIN.FK_ProjectCode, -1) AS Project,
                    ISNULL(RESERVATIONMAIN.StaffID, -1) AS StaffID,
                    CASE WHEN((Rooms.CustomerNumber IS NOT NULL
                                AND RESERVATIONADDRESS.LINK IS NOT NULL)
                            AND Rooms.CustomerNumber = RESERVATIONADDRESS.LINK) THEN 1
                        ELSE 0
                    END AS OwnerReservation,
                    RESERVATIONS.SplitBill,
		            RoomTypes.HotelNumber as roomTypeHotelNumber,
		            FK_ReferenceNumber
            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, 3, 5, 6, 7, 8))
                                                            OR (@IncludeTentative = 1
                                                                AND RESERVATIONS.STATUS IN(0, 1, 2, 3, 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 dbo.Rooms WITH (NOLOCK) ON ReservationRoomLine.RoomNumber = Rooms.RoomNumber
                LEFT OUTER JOIN dbo.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 @CentralBookingType = 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, 
		                                 @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;
        END; -- RoomLine
        ELSE -- 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) as Status,
		                RESERVATIONS.MARKETSEGMENT,
                    RESERVATIONS.POINTOFSALE,
                    RESERVATIONConferenceLINE.PriceOverWritten,
                    RESERVATIONConferenceLINE.Adults,
                    RESERVATIONConferenceLINE.Children1,
                    RESERVATIONConferenceLINE.Children2,
                    RESERVATIONConferenceLINE.Price,
                    RESERVATIONConferenceLINE.ReferenceNumber,
                    RESERVATIONConferenceLINE.PackageNumber,
                    RESERVATIONConferenceLINE.ArrivalTime,
                    RESERVATIONConferenceLINE.DepartureTime,
                    ISNULL(Customer.CustomerNumber, -1),
                    ISNULL(ReservationConferenceLine.Plenum, 0),
                    ISNULL(RESERVATIONS.FK_CampaignCode, -1),
                    ISNULL(RESERVATIONMAIN.FK_ProjectCode, -1),
                    ISNULL(RESERVATIONMAIN.StaffID, -1),
                    0 AS OwnerReservation,
                    RESERVATIONS.SplitBill,
		                0 AS RoomTypeHotelNumber, -- ikke for halls
		                FK_ReferenceNumber,
					          RESERVATIONConferenceLINE.TableBooking
            FROM RESERVATIONConferenceLINE WITH (NOLOCK)
                INNER JOIN Reservations WITH (NOLOCK) ON Reservations.ReferenceNumber = RESERVATIONConferenceLINE.ReferenceNumber --AND Reservations.GuestNumber = 0 
                                                            AND ((@IncludeTentative = 0
                                                                AND RESERVATIONS.STATUS IN(0, 1, 2, 3, 5, 6, 7, 8))
                OR (@IncludeTentative = 1
                    AND RESERVATIONS.STATUS IN(0, 1, 2, 3, 4, 5, 6, 7, 8)))
            --AND (TableBooking = 0 OR TableBooking is null) 
            AND RESERVATIONS.ReferenceNumber > 0 
            /*  ny fra kent  */
            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 @CentralBookingType = 7
                                                            AND ISNULL(Customer.MarkAsDeleted, 0) = 0
                LEFT OUTER JOIN ConferenceRooms WITH (NOLOCK) ON RESERVATIONConferenceLINE.Conferenceroomnumber = ConferenceRooms.Conferenceroomnumber
                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 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, @PriceOverWritten, @Adults, @Children1, @Children2, @Price, @ReferenceNumber, 
											@PacketNumberReservation, @ArrArrivalTime, @ArrDepartureTime, @HotelCustomerNumber, @Plenum, 
											@CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber, @RoomTypeHotelNumber, 
											@FK_ReferenceNumber, @IsTableBooking;

        END;  --ConfLine
        SET @PrevLineNumber = 0;
        SET @PrevReferenceNumber = 0;
        SET @GetVatValueFromProduct2 = 0;
        SET @GetVatValueFromProduct3 = 0;
        SET @GetVatValueFromProduct4 = 0;
        
	  Declare @MainCourceNoValues bit --should amounts, adults etc. be reset to 0

		WHILE(@@FETCH_STATUS <> -1)
    BEGIN
	  --@BookedTypeNumber, @LINENUMBER, @RoomNumber, @ArrivalDate, @DepartureDate, @ProductNumber, @NumberOfRooms, @Status, @PriceOverWritten, @Adults, @Children1, @Children2, @Price, @ReferenceNumber, @PacketNumberReservation, @ArrArrivalTime, @ArrDepartureTime, @HotelCustomerNumber, @Plenum, @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber;
	  If ((ISNULL(@FK_ReferenceNumber, 0) = 0) --not a main course res.
              OR @MainCourceResNotInclMIS_OrderBook = 0)
	  Begin
	    SET @MainCourceNoValues = 0
	  End Else
	  Begin
	    SET @MainCourceNoValues = 1
	  End;

          BEGIN
            SET @TmpProductNumber = NULL;
            IF ISNULL(@LINENUMBER, 0) = 0
            BEGIN
            SET @LINENUMBER = 0
            END;
            SET @StarProduct = 0;
            IF ISNULL(@ROOMNUMBER, 0) = 0
            BEGIN
            SET @ROOMNUMBER = 0
            END;
            SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1;
            IF @TableCount = 2 --Hall
            BEGIN
              SET @guestnumber = 0;
              SET @ConflineOnMainRes = 0;
              SET @AllocatedTypeNumber = @BookedTypeNumber;
              IF ISNULL(@BookedTypeNumber, 0) = 0
              BEGIN
                SET @DepartureDate = CONVERT(CHAR(8), CONVERT(DATETIME, @DepartureDate) - 1, 112)
              END;
              IF ISNULL(@AllocatedTypeNumber, 0) = 0
              BEGIN
                SET @AllocatedTypeNumber = 0
              END;
              IF(@ArrDepartureTime < @Arr24)
                AND (@BookedTypeNumber > 0)
              BEGIN
                SET @DepartureDate = CONVERT(CHAR(8), CONVERT(DATETIME, @DepartureDate) - 1, 112)
              END;
              IF @ArrArrivalTime < @Arr24
              BEGIN
                SET @ArrivalDate = CONVERT(CHAR(8), CONVERT(DATETIME, @ArrivalDate) - 1, 112)
              END;
            END;
            ELSE
            BEGIN --Room
              SET @AllocatedTypeNumber = @BookedTypeNumber;
              IF ISNULL(@Price, 0) = 0
              BEGIN
                SET @Price = 0
              END;
              IF ISNULL(@TotalPrice, 0) = 0
              BEGIN
                SET @TotalPrice = 0
              END;
              IF ISNULL(@Day2, 0) = 0
              BEGIN
                SET @Day2 = 0
              END;
              IF ISNULL(@Day3, 0) = 0
              BEGIN
                SET @Day3 = 0
              END;
              IF ISNULL(@Day4, 0) = 0
              BEGIN
                SET @Day4 = 0
              END;
              IF ISNULL(@ProductNumber, 0) = 0
              BEGIN
                SET @ProductNumber = 0
              END;
              IF ISNULL(@ProductNumber2, 0) = 0
              BEGIN
                SET @ProductNumber2 = 0
              END;
              IF ISNULL(@ProductNumber3, 0) = 0
              BEGIN
                SET @ProductNumber3 = 0
              END;
              IF ISNULL(@ProductNumber4, 0) = 0
              BEGIN
                SET @ProductNumber4 = 0
              END;
              IF ISNULL(@AllocatedTypeNumber, 0) = 0
              BEGIN
                SET @AllocatedTypeNumber = 0
              END;
              IF((@Day2 + @Day3 + @Day4) > 0)
              BEGIN
                SET @StarProduct = 1;
                IF @NameListSetting = 0
                BEGIN
                  SET @NameListSetting = @NameListSettingHotelSetup
                END;
              END;
              ELSE
              BEGIN
                IF @ProductNumber > 0
                BEGIN
                  IF @GuestNumber = 0
                  BEGIN
                    SET @NameListSetting = 0
                  END;
                  IF @NameListSetting = 0
                  BEGIN
                    SELECT @NameListSetting = NameListSetting
                    FROM Products WITH (NOLOCK)
                    WHERE productnumber = @ProductNumber;
                    IF ISNULL(@NameListSetting, 0) = 0
                    BEGIN
                      SET @NameListSetting = 0
                    END;
                  END;
                END;
                ELSE
                BEGIN
                  SET @NameListSetting = 0;
                END;
                IF @NameListSetting = 0
                BEGIN
                  SET @NameListSetting = @NameListSettingHotelSetup
                END;
              END;
            END; --Room
            IF ISNULL(@NumberOfRooms, 1) = 1
            BEGIN
              SET @NumberOfRooms = 1
            END;
            IF ISNULL(@Adults, 0) = 0
            BEGIN
              SET @Adults = 0
            END;
            IF ISNULL(@Children1, 0) = 0
            BEGIN
              SET @Children1 = 0
            END;
            IF ISNULL(@Children2, 0) = 0
            BEGIN
              SET @Children2 = 0
            END;
            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;


--If @ReferenceNumber = 202714
--Begin
--  Print 'WARENUMBER FOR PRODUCT'
--  Print '@WareGroupNumberProduct=' + convert(varchar, @WareGroupNumberProduct) +
--        ', @WareNumberProduct=' + convert(varchar, @WareNumberProduct) + ', @WareText=' + @WareText
--End


            END;
            IF ISNULL(@VatValueRoomProduct1, 0) = 0
            BEGIN
            SET @VatValueRoomProduct1 = 0
            END;
            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;
            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) --not Dayproduct (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
                    BEGIN
                        SET @PriceOverwrittenValue = 0;
                    END;
                    IF(@AddonIfPriceOverwritten = 0)
                    BEGIN
                        SET @Addon1 = 0
                    END;
                    END;
                    IF(@CurrentDateStr <> @DepartureDate)
                    OR (@ArrivalDate = @DepartureDate)
                    BEGIN
                    SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1
                    END;
                    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, --discount her
                        @ProductWareLinkNumber
                    END;
                END;
                ELSE -- StarProduct = +product   
                BEGIN
                    SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate);
                    SET @TmpProductEndDate = CONVERT(DATETIME, @ArrivalDate) + @Day2 - 1;
                    IF(@CurrentDate <= @TmpProductEndDate) -- ProductNumber incl afrejse pakke    
                    BEGIN
                    SET @ProductStartDate = @TmpProductStartDate;
                    SET @ProductEndDate = @TmpProductEndDate;
                    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
                        BEGIN
                          SET @PriceOverwrittenValue = 0;
                        END;
                        IF(@AddonIfPriceOverwritten = 0)
                        BEGIN
                          SET @Addon1 = 0
                        END;
                    END;
                    IF(@ProductStartDate <> @ProductEndDate)
                        AND (@CurrentDate <> @ProductEndDate)
                    BEGIN
                        SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1
                    END;
                    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, --discount
                        @ProductWareLinkNumber;
                    END;
                    IF(@Day3 = 0)
                    BEGIN
                    SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate) + @Day2 - 1;
                    SET @TmpProductEndDate = CONVERT(DATETIME, @DepartureDate);
                    IF(@CurrentDate >= @TmpProductStartDate)
                    BEGIN
                        SET @ProductStartDate = @TmpProductStartDate;
                        SET @ProductEndDate = @TmpProductEndDate;
                        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
                        BEGIN
                            SET @PriceOverwrittenValue = 0;
                        END;
                        IF(@AddonIfPriceOverwritten = 0)
                        BEGIN
                            SET @Addon2 = 0
                        END;
                        END;
                        IF(@ProductStartDate <> @ProductEndDate)
                        AND (@CurrentDate <> @ProductEndDate)
                        BEGIN
                        SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1
                        END;
                        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
                    BEGIN
                    SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate) + @Day2 - 1;
                    SET @TmpProductEndDate = CONVERT(DATETIME, @ArrivalDate) + @Day3 - 1;
                    IF(@CurrentDate >= @TmpProductStartDate)
                        AND (@CurrentDate <= @TmpProductEndDate)
                    BEGIN
                        SET @ProductStartDate = @TmpProductStartDate;
                        SET @ProductEndDate = @TmpProductEndDate;
                        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
                        BEGIN
                            SET @PriceOverwrittenValue = 0;
                        END;
                        IF(@AddonIfPriceOverwritten = 0)
                        BEGIN
                            SET @Addon2 = 0
                        END;
                        END;
                        IF(@ProductStartDate <> @ProductEndDate)
                        AND (@CurrentDate <> @ProductEndDate)
                        BEGIN
                        SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1
                        END;
                        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
                        SET @ProductStartDate = @TmpProductStartDate;
                        SET @ProductEndDate = @TmpProductEndDate;
                        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
                            BEGIN
                            SET @PriceOverwrittenValue = 0;
                            END;
                            IF(@AddonIfPriceOverwritten = 0)
                            BEGIN
                            SET @Addon3 = 0
                            END;
                        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;
                    END; --Day4 = 0
                    ELSE
                    BEGIN
                        SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate) + @Day3 - 1;
                        SET @TmpProductEndDate = CONVERT(DATETIME, @ArrivalDate) + @Day4 - 1;
                        IF(@CurrentDate >= @TmpProductStartDate)
                        AND (@CurrentDate <= @TmpProductEndDate)
                        BEGIN
                        SET @ProductStartDate = @TmpProductStartDate;
                        SET @ProductEndDate = @TmpProductEndDate;
                        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
                            BEGIN
                            SET @PriceOverwrittenValue = 0;
                            END;
                            IF(@AddonIfPriceOverwritten = 0)
                            BEGIN
                            SET @Addon3 = 0
                            END;
                        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;
                        SET @TmpProductStartDate = CONVERT(DATETIME, @ArrivalDate) + @Day4 - 1;
                        SET @TmpProductEndDate = CONVERT(DATETIME, @DepartureDate);
                        IF(@CurrentDate >= @TmpProductStartDate)
                        AND (@CurrentDate <= @TmpProductEndDate)
                        BEGIN
                        SET @ProductStartDate = @TmpProductStartDate;
                        SET @ProductEndDate = @TmpProductEndDate;
                        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
                            BEGIN
                            SET @PriceOverwrittenValue = 0;
                            END;
                            IF(@AddonIfPriceOverwritten = 0)
                            BEGIN
                            SET @Addon4 = 0
                            END;
                        END;
                        IF(@ProductStartDate <> @ProductEndDate)
                            AND (@CurrentDate <> @ProductEndDate)
                        BEGIN
                            SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1
                        END;
                        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 Not DayProduct   
                        ;
                ELSE -- Dayproduct (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)
                    BEGIN
                    EXEC CalcPacketPriceAccExt
                        1,
                        @AllocatedTypeNumber,
                        @CurrentDateStr,
                        @PacketNumber,
                        @ProductNumber,
                        @Adults,
                        @Children1,
                        @Children2,
                        1,
                        @HotelCustomerNumber,
                        @PackagePriceProduct1 OUTPUT,
                        @VatByPacketValueProduct1 OUTPUT,
                        1, /*NameListSetting must be 1*/
                        0,
                        @PriceOverwritten,
                        @FixedPrice, 
                        1,/*PackageDepartment*/
                        @Referencenumber,
                        @GuestNumber,
                        @PriceProduct1,
                        0,
                        @ProductWareLinkNumber;
                    END
                    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
                        BEGIN
                            SET @Price = 0
                        END;
                        SET @PriceProduct1 = @Price * @NumberOfRooms;
                        END;
                    END;
                    ELSE
                    BEGIN
                        IF(@PriceOverWritten = 1)
                        BEGIN
                        IF ISNULL(@Price, 0) = 0
                        BEGIN
                            SET @Price = 0
                        END;
                        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, /*NameListSetting must be 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,  /*NameListSetting must be 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
                BEGIN
                    SET @ValueType = 3;
                END
                ELSE
                BEGIN
                    SET @ValueType = 2;
                END;
              END; -- End DayProduct   
            --END; -- END Booked values   

            IF(@CurrentDateStr = @DepartureDate) --sidste dag af flere
                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 @TableCount = 1
                    AND (@SmallestArrivalDate <= @CurrentDateStr)
                    AND (((@BiggestDepartureDate >= @CurrentDateStr)
                        AND (@DepartureDate <= @BiggestDepartureDate))
                        OR ((@BiggestDepartureDate > @CurrentDateStr)
                            AND (@DepartureDate > @BiggestDepartureDate)))
                    AND @ArrivalDate >= @SmallestArrivalDate
                BEGIN
                    SET @BookedNumberOfRooms = 0;
                END;
                ELSE
                BEGIN
                    SET @BookedNumberOfRooms = @NumberOfRooms;
                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 @TableCount = 1
                AND (@SmallestArrivalDate <= @CurrentDateStr)
                AND (((@BiggestDepartureDate >= @CurrentDateStr)
                        AND (@DepartureDate <= @BiggestDepartureDate))
                        OR ((@BiggestDepartureDate > @CurrentDateStr)
                            AND (@DepartureDate > @BiggestDepartureDate)))
                AND @ArrivalDate >= @SmallestArrivalDate
                BEGIN
                SET @BookedNumberOfRooms = 0;
                END;
                ELSE
                BEGIN
                SET @BookedNumberOfRooms = @NumberOfRooms;
                END;
                IF ISNULL(@PriceProduct1, 0) = 0
                BEGIN
                SET @PriceProduct1 = 0
                END;
                IF ISNULL(@PriceProduct2, 0) = 0
                BEGIN
                SET @PriceProduct2 = 0
                END;
                IF ISNULL(@PriceProduct3, 0) = 0
                BEGIN
                SET @PriceProduct3 = 0
                END;
                IF ISNULL(@PriceProduct4, 0) = 0
                BEGIN
                SET @PriceProduct4 = 0
                END;
                IF ISNULL(@Addon1, 0) = 0
                BEGIN
                SET @Addon1 = 0
                END;
                IF ISNULL(@Addon2, 0) = 0
                BEGIN
                SET @Addon2 = 0
                END;
                IF ISNULL(@Addon3, 0) = 0
                BEGIN
                SET @Addon3 = 0
                END;
                IF ISNULL(@Addon4, 0) = 0
                BEGIN
                SET @Addon4 = 0
                END;
                IF ISNULL(@NumberOfRooms, 0) = 0
                BEGIN
                SET @NumberOfRooms = 1
                END;
                IF((@TableCount = 2)
                OR ((@StarProduct = 0)
                    AND (@TableCount = 1))) --not Dayproduct
                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
            BEGIN
                SET @SegmentNumber = 0
            END;
            IF(@SegmentNumber = 0)
            BEGIN
                SELECT @SegmentNumber = Number
                FROM Segments WITH (NOLOCK)
                WHERE((MarkAsDeleted = '0')
                    OR (MarkAsDeleted IS NULL))
            END;
            IF ISNULL(@PointOfSaleNumber, 0) = 0
            BEGIN
                SET @PointOfSaleNumber = 0
            END;
            IF(@PointOfSaleNumber = 0)
            BEGIN
                SELECT @PointOfSaleNumber = Number
                FROM PointOfSales WITH (NOLOCK)
                WHERE((MarkAsDeleted = '0')
                    OR (MarkAsDeleted IS NULL))
            END;
            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)
            BEGIN
                DELETE FROM #PacketWareTable
            END;

            --*** 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,
                    @AllocatedTypeNumber,
                    @CampaignCode,
                    @ProjectCode,
                    @StaffID,
                    @OwnerReservation,
                    @DiscountResultAccountNumber;
                INSERT INTO #ReferenceExtrasTable
                VALUES
                (@ReferenceNumber,
                @CurrentDateStr
                );
            END;

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

            -- Store Logi
            IF @TableCount = 1 --Room
            BEGIN
              SELECT TOP 1 @DepartmentNumber = d.PK_Department
              FROM Departments d
              WHERE d.HotelNumber = ISNULL(@RoomTypeHotelNumber, 0)
              AND ISNULL(d.MarkAsDeleted, 0) = 0 
              AND d.AutoCharge = 1    
            END ELSE
            BEGIN  --Hall
              SELECT TOP 1 @DepartmentNumber = PK_Department
              FROM Departments d WITH (NOLOCK)
              INNER JOIN ReservationMain r WITH (NOLOCK) ON d.HotelNumber = r.HotelNumber
                                                            AND AutoCharge = 1
                                                            AND ISNULL(MarkAsDeleted, 0) = 0
                                                            AND ReferenceNumber = @ReferenceNumber;
            END
            SET @DepartmentNumber = ISNULL(@DepartmentNumber, -1);
	    If @MainCourceNoValues = 1
	    Begin
	      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

	    --print Convert(varchar, @TableCount) + ', @RoomTypeHotelNumber=' + convert(varchar, @RoomTypeHotelNumber) + ' @DepartmentNumber=' + convert(varchar, @DepartmentNumber)
      
      SET @ResultAccountNumber = ISNULL(@ResultAccountNumber, -1);
 
		  EXEC MisStoreLogiAndCalcDiscount
                @Room_HallType,
                @OrderBookBudgetCalcDiscount,
                @DiscountAsNettoPrice,
                @ChargeDiscountAsProduct,
                @DiscountVatValueWare,
                @SplitBillNumber,
                @FixedPrice,
                @tmpUpdateType,
                @tmpSameDayAsLogi,
                @ValueType,
                @BookedNumberOfRooms,
                @TotalAdults,
                @TotalChildren1,
                @TotalChildren2,
                @ReferenceNumber,
                @GuestNumber,
                --@FolioNumber,
                @SystemDateStr,
                @CurrentDateStr,
                @CurrentDateStrDeparturePackage,
                @SegmentNumber,
                @PointOfSaleNumber,
                @AllocatedTypeNumber,
                @HotelCustomerNumber,
                @Status,
                @CampaignCode,
                @ProjectCode,
                @StaffID,
                @WareGroupNumberProduct,
                @WareNumberProduct,
                @OwnerReservation,
                @DepartmentNumber,
                @tmpProductWareLinkNumberMis,
                @ResultAccountNumber,
                @DiscountResultAccountNumber,
                @TotalPriceDay,
                @VatOfPrice,
                @PackagePrice,
                @VatOfPacket,
                @TmpProductNumber;

            -- Store addons
            IF(@Addon <> 0 OR @VatOfAddon <> 0) and (@MainCourceNoValues = 0)
            BEGIN
              SET @TempCurrentDateStr = @CurrentDateStr;
              IF @Room_HallType = 0
              BEGIN
                IF(@CurrentDateStr = @DepartureDate)
                BEGIN
                    SET @TempCurrentDateStr = CONVERT(CHAR(8), @CurrentDate - 1, 112)
                END
              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
              Begin
                Set @tmpAddonAccountNumber = @ResultAccountNumber
              End
			        Declare @TotalPax int = @TotalAdults + @TotalChildren1 + @TotalChildren2;
              
              EXEC UpdateMISTable
                    @SystemDateStr,
                    @Room_HallType,
                    @ReferenceNumber,
                    @GuestNumber,
                    -- -1, --FolioNumber
                    @tmpUpdateType,
                    @tmpSameDayAsLogi,
                    0, --@BookedNumberOfRooms
                    0, --@TotalAdults
                    0, --@TotalChildren1
                    0, --@TotalChildren2
                    @Addon,      --@TotalPriceDay
                    @VatOfAddon, --@VatOfPrice
                    0,           --@VatOfPacket
                    0,           --@PackagePrice
                    @TempCurrentDateStr,
                    @CurrentDateStrDeparturePackage,
                    @SegmentNumber,
                    @PointOfSaleNumber,
                    @AllocatedTypeNumber,
                    @ValueType,
                    @HotelCustomerNumber,
                    @Status,
                    @CampaignCode,
                    @ProjectCode,
                    @StaffID,
                    @WareGroupNumber,
                    @tmpAddonAccountNumber,
                    @DepartmentNumber,
                    -1,  --@ProductWareLinkNumber
                    0,   --@IsPackage
                    @AddonWareText,  
                    @OwnerReservation,
                    @TmpProductNumber,
                    @tmpAddonWareType,
                    @tmpAddOnWareNumber,
					          @TotalPax     --@BookedWareCount

--print 'Addon, @ReferenceNumber=' + convert(varchar, @ReferenceNumber) + ', @AddonWareText=' + ', @WareNumber=' + convert(varchar, @WareNumber) + ', @Addon=' + convert(varchar, @Addon)

            END;

      Declare @DayProductLocal bit
			If @TableCount = 1 --Room
			Begin
			  Set @DayProductLocal = 0
      End Else
			Begin
			  Set @DayProductLocal = 1
			End
            IF(@CurrentDate < @SystemDate - 1)
            BEGIN
              IF(@Plenum = 0)
              BEGIN
                SET @tmpUpdateType = 1;
              END ELSE
              BEGIN
                SET @tmpUpdateType = 2;
              END;
            END;
            ELSE
            BEGIN
              IF(@Plenum = 0)
              BEGIN
                SET @tmpUpdateType = 3;
              END ELSE
              BEGIN
                SET @tmpUpdateType = 4;
              END;
            END;
			--per reservation, per day
	
			EXEC MISCalcProvision @SystemDateStr,
			                      @CurrentDateStr,
                            @CurrentDateStrDeparturePackage,
			                      @Room_HallType,
			                      @ReferenceNumber,
                                  @GuestNumber,
                                  @TotalPriceDay,
                                  @Addon,
                                  @DayProductLocal,  --Hall: 1, room: 0
								  @tmpUpdateType,
								  @SplitBillNumber,
								  --@TableReservationLineNumber, --RESERVATIONConferenceLINE.ReservationConfLineNumber if RESERVATIONConferenceLINE.TableBooking=1
								  @Room_HallType,  --Room or Hall BookedTypeNumber
			                      @PackageSameDayAsLogi,
								  @SegmentNumber, 
	                              @PointOfSaleNumber,
								  @AllocatedTypeNumber,
                                  @HotelCustomerNumber,
                                  @Status,
                                  @CampaignCode,
                                  @ProjectCode,
                                  @StaffID,
                                  @DepartmentNumber,
                                  @ProductWareLinkNumber, 
	                              0, --@IsPackage, 
	                              @Text,
	                              @OwnerReservation,
	                              @ProductNumber
			

            -- Store Packages
            --select * from #PacketWareTable (nolock)

            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;
            IF(@CurrentDate >= @SystemDate)
            BEGIN
                SET @PackageStored = 0;
                IF(@@FETCH_STATUS <> -1)
                BEGIN
                SET @PackageStored = 1
                END;
                WHILE(@@FETCH_STATUS <> -1)
                BEGIN
                

                --				if (@CurrentDate = @ProductEndDate) and (@CurrentDate = @SystemDate)
                IF(@CurrentDate = @SystemDate)
                BEGIN
                    IF @TableCount = 2
                    OR @SystemDate < @ProductEndDate
                    BEGIN -- SG/20121219
                      SET @ProductWareLinkNumberMis = -200 -- Later in MisUpdateProductWareLinkNumbers this packet will be pared with product that is already posted in actual
                    END
                    ELSE
                    BEGIN
                      SET @ProductWareLinkNumberMis = -100;
                    END; -- SG/20130124: Room-package on departure day comes from transaction and should not be included here.
                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,
                        -- -1,
                        @tmpUpdateType,
                        @tmpSameDayAsLogi,
                        0, --@BookedNumberOfRooms
                        0, --@TotalAdults
                        0, --@TotalChildren1
                        0, --@TotalChildren2
                        0, --@TotalPriceDay
	                      0, --@VatOfPrice
                        @VatOfPacketWarePrice,
                        @PacketWarePrice,
                        @CurrentDateStr,
                        @CurrentDateStrDeparturePackage,
                        @SegmentNumber,
                        @PointOfSaleNumber,
                        @AllocatedTypeNumber,
                        @ValueType,
                        @HotelCustomerNumber,
                        @Status,
                        @CampaignCode,
                        @ProjectCode,
                        @StaffID,
                        @WareGroupNumber,
                        @ResultAccountPackage,
                        @DepartmentNumberPackage,
                        @ProductWareLinkNumberMis,
                        1,
                        @WareName,
						            @OwnerReservation,
                        @ProductNumberPacket,
                        @WareType,
                        @WareNumber,
						            @BookedWareCountPacket;
--print 'Packages, @ReferenceNumber=' + convert(varchar, @ReferenceNumber) + ', @WareName=' + @WareName + ', @WareNumber=' + convert(varchar, @WareNumber) + ', @PacketWarePrice=' + convert(varchar, @PacketWarePrice)

                      EXEC MISCalcProvision @SystemDateStr,
			                      @CurrentDateStr,
                            @CurrentDateStrDeparturePackage,
			                      @Room_HallType,
			                      @ReferenceNumber,
                            @GuestNumber,
                            @PacketWarePrice,
                            0, --@Addon
                            @DayProductLocal,  --Hall: 1, room: 0
								            @tmpUpdateType,
								            @SplitBillNumber,
								            --@TableReservationLineNumber, --RESERVATIONConferenceLINE.ReservationConfLineNumber if RESERVATIONConferenceLINE.TableBooking=1
								            @Room_HallType,  --Room or Hall BookedTypeNumber
			                      @PackageSameDayAsLogi,
								            @SegmentNumber, 
	                          @PointOfSaleNumber,
								            @AllocatedTypeNumber,
                            @HotelCustomerNumber,
                            @Status,
                                  @CampaignCode,
                                  @ProjectCode,
                                  @StaffID,
                                  @DepartmentNumber,
                                  @ProductWareLinkNumber, 
	                              1, --@IsPackage, 
	                              @Text,
	                              @OwnerReservation,
	                              @ProductNumber
			

                    END;
                END;
                FETCH NEXT FROM PacketWareCur INTO @ResultAccountPackage, @DepartmentNumberPackage, @PacketWarePrice, @VatOfPacketWarePrice, 
                                                   @WareGroupNumber, @WareName, @WareType, @WareNumber,
                                                   @ProductWareLinkNumberMis, @ProductNumberPacket, @BookedWareCountPacket;
              END;
            END;
            IF(@TableCount <> 1)
            BEGIN -- DayProduct
                SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1;
            END;
            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   
        END; -- End @PrevLineNumber<>@LINENUMBER   

        SET @OneDayBack = 0;
        IF @LINENUMBER = @PrevLineNumber
        BEGIN
            IF @ArrivalDate < @SmallestArrivalDate
            BEGIN
            SET @SmallestArrivalDate = @ArrivalDate
            END;
            IF @BiggestDepartureDate < @DepartureDate
            BEGIN
            SET @BiggestDepartureDate = @DepartureDate
            END;
        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,
			                             @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;
        END;
        ELSE
        BEGIN
          FETCH NEXT FROM ReservationCur INTO @Room_HallType, @BookedTypeNumber, @LINENUMBER, @RoomNumber, @ArrivalDate, @DepartureDate, @ProductNumber, @NumberOfRooms, 
		                                 @Status, @SegmentNumber, @PointOfSaleNumber, @PriceOverWritten, @Adults, @Children1, @Children2, @Price, @ReferenceNumber, 
										 @PacketNumberReservation, @ArrArrivalTime, @ArrDepartureTime, @HotelCustomerNumber, @Plenum, 
										 @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber, @RoomTypeHotelNumber, 
										 @FK_ReferenceNumber, @IsTableBooking
        END;
      END; -- Fetch ReservationCur  

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



     PRINT '***************** Transaction section ************************'
     RAISERROR(N'', 0, 1) WITH NOWAIT

     IF(@CalcSystemDateOnly = 1)
     BEGIN
       SET @FormatedStartDate = @SystemDateStr
     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  --From SMS-import, not to be mixed with -1 meening "no folio" = from reservation
				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,
                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(Transactions.MovedDeleted = 1) THEN 1
                    ELSE 0
                END AS Correction,
                CASE WHEN PERSONEL.UserTypeNumber NOT IN(3, 4) THEN 1
                    ELSE 0
                END AS ManuelUser,
                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.GlobalTransactionNumber,
                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 Accounts.Balance = 2
                          AND Accounts.AccountType IN(5) THEN 1
                    ELSE 0
                END AS InhouseDebitor,
                PERSONEL.UserTypeNumber,
                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
         FROM transactions WITH (NOLOCK)
              INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = Transactions.FolioNumber
              LEFT OUTER JOIN FolioRestResTableChairsXTab WITH (NOLOCK) ON FolioRestResTableChairsXTab.FolioNumber = Folios.FolioNumber
              LEFT OUTER JOIN RESERVATIONADDRESS WITH (NOLOCK) ON RESERVATIONADDRESS.AddressNumber = Folios.ReservationAddressNumber 
              LEFT OUTER JOIN customer WITH (NOLOCK) ON RESERVATIONADDRESS.link = customer.CustomerNumber
              LEFT OUTER JOIN Reservations WITH (NOLOCK) ON Folios.ReferenceNumber = Reservations.ReferenceNumber
                                                            AND Folios.GuestNumber = Reservations.GuestNumber
              LEFT OUTER JOIN RESERVATIONMAIN WITH (NOLOCK) ON Folios.ReferenceNumber = RESERVATIONMAIN.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 PERSONEL WITH (NOLOCK) ON PERSONEL.UserIDNumber = Transactions.UserIDNumber
              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 Accounts.Balance = 1
              AND Accounts.AccountType NOT IN (1, 2)
              AND -- Accounts transactions
              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(FK_ReferenceNumber, 0) = 0          --not a main course res.
            --        OR @MainCourceResNotInclMIS_OrderBook = 0) --incl main course res.

         ORDER BY ISNULL(Folios.Referencenumber, -1),
                  ISNULL(Transactions.ProductWareLinkNumber, -1),
                  CONVERT( CHAR(8), Transactions.DateStamp, 112);
     OPEN TransCur;

    Declare @ActualWareCount int 
    FETCH NEXT FROM TransCur INTO @tmpTransdate, @ReferenceNumber, @FolioNumber, @Totalsum, @SegmentNumber, @PointOfSaleNumber, @MisType, @WarePayment, @VatValueWare, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @Correction, @ManuelUser, @IsPackage, @WareGroupNumber, @GlobalTransactionNumber, @TransactionNumber, @Adults, @Children1, @Children2, @Pieces, @Debit, @ProductNumber, @ProductWareLinkNumber, @ResultAccountNumber, @ShowOnBillFlag, @DepartmentNumber, @GuestNumber, @FixedPrice, @DayProduct, @InhouseDebitor, @UserTypeNumber, @TransactionMoved, @TransactionDeleted, @FK_ReferenceNumber, 
	                              @WareType, @WareNumber, @Text;

	  SET @tmpProductWareLinkNumberTrans = -1;
    SET @Room_HallType = 0;
    WHILE(@@FETCH_STATUS <> -1)
    BEGIN
     Set @ActualWareCount = @Pieces; --Negative, when debit = 1
     If ((ISNULL(@FK_ReferenceNumber, 0) = 0) --not a main course res.
          OR @MainCourceResNotInclMIS_OrderBook = 0)
     Begin
       SET @MainCourceNoValues = 0
     End Else
     Begin
       SET @MainCourceNoValues = 1
     End;
   
       IF @PackageSameDayAsLogi = 1
       BEGIN
         IF @ProductWareLinkNumber <= 0
         BEGIN
           SET @TransDate = @tmpTransDate -- Do nothing
           ;
         END
         ELSE
         BEGIN
           IF(@ProductWareLinkNumber > 0)
             AND (@tmpProductWareLinkNumberTrans <> @ProductWareLinkNumber)
           BEGIN
             SET @TransDate = @tmpTransdate
           END;
         END; -- Get the first date in the serie of a ProductWareLinkNumber	
         SET @tmpProductWareLinkNumberTrans = @ProductWareLinkNumber;
       END;
       ELSE
       BEGIN
         SET @TransDate = @tmpTransdate;
       END;
       IF ISNULL(@PointOfSaleNumber, 0) = 0
       BEGIN
         SET @PointOfSaleNumber = @DefaultMISPointOfSale
       END;
       IF ISNULL(@SegmentNumber, 0) = 0
       BEGIN
         SET @SegmentNumber = @DefaultMISSegment
       END;
       IF @ProductWareLinkNumber = 0
       BEGIN
         SET @ProductWareLinkNumber = -1
       END;
       IF ISNULL(@MisType, -1) = -1
       BEGIN
         SET @MisType = 1
       END;
       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((@WarePayment = 2)
          OR (@WarePayment = 7))
         OR ((@IsPackage = 1)
             AND (@DayProduct = 0)) -- (AutoRoom or ManualRooms) or (if package and nigthproduct)
       BEGIN
         SELECT @RoomTypeNumber = ISNULL(Rooms.RoomTypeNumber /*allocated roomtype*/
                , ISNULL(RoomTypes.RoomTypeNumber /*booked roomtype*/
                , 0)),
                @ArrivalDate = CASE RESERVATIONS.GuestNumber WHEN 0 THEN CASE ISNULL(RESERVATIONROOMLINE.LineNumber, 0) WHEN 0 THEN RESERVATIONS.ArrivalDate
                                                                             ELSE RESERVATIONROOMLINE.ArrivalDate
                                                                         END
                                   ELSE RESERVATIONS.ArrivalDate
                               END,
                @DepartureDate = CASE RESERVATIONS.GuestNumber WHEN 0 THEN CASE ISNULL(RESERVATIONROOMLINE.LineNumber, 0) WHEN 0 THEN RESERVATIONS.DepartureDate
                                                                               ELSE RESERVATIONROOMLINE.DepartureDate
                                                                           END
                                     ELSE RESERVATIONS.DepartureDate
                                 END,
                @OwnerReservation = CASE WHEN((Rooms.CustomerNumber IS NOT NULL
                                               AND RESERVATIONADDRESS.LINK IS NOT NULL)
                                              AND Rooms.CustomerNumber = RESERVATIONADDRESS.LINK) THEN 1
                                        ELSE 0
                                    END
         FROM RESERVATIONROOMLINE WITH (NOLOCK)
              INNER JOIN RESERVATIONROOMLINEXTAB WITH (NOLOCK) ON RESERVATIONROOMLINE.LINENUMBER = RESERVATIONROOMLINEXTAB.LINENUMBER
              INNER JOIN RESERVATIONS WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.ReferenceNumber = RESERVATIONS.ReferenceNumber
                                                       AND RESERVATIONROOMLINEXTAB.GuestNumber = RESERVATIONS.GuestNumber
              INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.ReferenceNumber = RESERVATIONS.ReferenceNumber
              LEFT OUTER JOIN dbo.Rooms WITH (NOLOCK) ON ReservationRoomLine.RoomNumber = Rooms.RoomNumber
              LEFT OUTER JOIN dbo.RoomTypes WITH (NOLOCK) ON ReservationRoomLine.BookedTypeNumber = RoomTypes.RoomTypeNumber
              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(RESERVATIONS.ReferenceNumber = @ReferenceNumber
               AND RESERVATIONS.GuestNumber = @GuestNumber);
       END ELSE
       BEGIN
         IF @WarePayment IN (3, 8) --Hall
         OR ((@IsPackage = 1) AND (@DayProduct = 1))
         Begin
           SET @Room_HallType = 1
           SELECT  @RoomTypeNumber = BookedConferenceRoomTypeNumber,
                   @ArrivalDate = ArrivalDate,
                   @DepartureDate = DepartureDate
           FROM  RESERVATIONCONFERENCELINE
           WHERE RESERVATIONCONFERENCELINE.ReferenceNumber = @ReferenceNumber
                 AND RESERVATIONCONFERENCELINE.GuestNo = @GuestNumber
           --print 'HALLS, ReferenceNumber=' + convert(varchar, @ReferenceNumber) + ', @RoomTypeNumber=' + convert(varchar, @RoomTypeNumber)
           --RAISERROR(N'', 0, 1) WITH NOWAIT
         End
       END
       SET @Adults = 0;
       SET @Children1 = 0;
       SET @Children2 = 0;
       SET @Pieces = 0;
       IF(@MisType = 1)
       BEGIN -- Other
         SET @ValueType = 5 -- Other
         ;
       END
       ELSE
       BEGIN
         IF(@MisType = 2)
         BEGIN -- Restaurant
           SET @ValueType = 4
         END;
       END; -- Restaurant


       IF(@WarePayment = 2)
         OR (@WarePayment = 7) -- AutoRoom or ManualRooms. Must not follow any mistype. Allways include in mis.
       BEGIN
         SET @ValueType = 1;
         GOTO Store;
       END;
       ELSE
       BEGIN
         IF(@WarePayment = 3)
           OR (@WarePayment = 8) -- AutoHall or ManualHalls. Must not follow any mistype. Allways include in mis.
         BEGIN
           IF(@ProductNumber <= 0)
           BEGIN
             SET @FixedPrice = 0;
           END;
           IF @FixedPrice = 0
           BEGIN -- Daymeetings
             SET @ValueType = 3;
           END
           ELSE
           BEGIN
             SET @ValueType = 2;
           END; -- Halls

           GOTO Store;
         END;
       END;
       IF(@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)
         BEGIN
           SET @ValueType = 1;
         END
         ELSE
         BEGIN
           IF(@FixedPrice = 0)
           BEGIN -- Daymeetings
             SET @ValueType = 3;
           END
           ELSE
           BEGIN
             SET @ValueType = 2;
           END; -- Halls
         END;
       END;
       --IF(@ValueType IN(2, 3))
       --BEGIN
       --  SET @RoomTypeNumber = 0
       --END; -- Catch and remove any roomtypes on halls and daymeetings 2021-03-22: Why?

       IF(@ShowOnBillFlag = 0 

       /*and @InhouseDebitor = 0*/

       )
       BEGIN
         SET @Totalsum = (@Totalsum) * CONVERT(FLOAT, ((@VatValueWare / 100) + 1));
         IF(@Debit = 1)
         BEGIN
           SET @Pieces = @Pieces * -1  --Now positive
         END; -- of

         IF(@TransDate < @SystemDateStr)
         BEGIN
           
	   If @MainCourceNoValues = 1
	   Begin
       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,
            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
           )
           VALUES
           (@TransDate,
            @ReferenceNumber,
            @FolioNumber,
            @SegmentNumber,
            @PointOfSaleNumber,
            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
           );
         END;
       END;
       Skip:
       FETCH NEXT FROM TransCur INTO @tmpTransdate, @ReferenceNumber, @FolioNumber, @Totalsum, @SegmentNumber, @PointOfSaleNumber, @MisType, @WarePayment, @VatValueWare, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @Correction, @ManuelUser, @IsPackage, @WareGroupNumber, @GlobalTransactionNumber, @TransactionNumber, @Adults, @Children1, @Children2, @Pieces, @Debit, @ProductNumber, @ProductWareLinkNumber, @ResultAccountNumber, @ShowOnBillFlag, @DepartmentNumber, @GuestNumber, @FixedPrice, @DayProduct, @InhouseDebitor, @UserTypeNumber, @TransactionMoved, @TransactionDeleted, @FK_ReferenceNumber, 
	                                 @WareType, @WareNumber, @Text;
     END;  --while
     CLOSE TransCur;
     DEALLOCATE TransCur;
     --END --Normal MIS calculation, (IF @CountResToRecalc = 0), transaction part
     Print '**** END Normal MIS calculation'
     RAISERROR(N'', 0, 1) WITH NOWAIT
     
	DROP TABLE #ReferenceExtrasTable;
     DROP TABLE #PacketWareTable;

--	If @CalcMISFromDate = ''
--	Begin
	    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
		 BEGIN
		   UPDATE Hotelsetup
			SET
			    KeyValue = 0
		   WHERE SearchKey = 'MISTotalCalcNeeded'
		 END
	    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;

	    PRINT 'Calc of real vat of Product price. MisTable (VatOfPriceCur)'
            RAISERROR(N'', 0, 1) WITH NOWAIT

	    DECLARE VatOfPriceCur CURSOR STATIC
	    FOR SELECT Room_HallType,
				MISTABLE.ReferenceNumber,
				GuestNumber,
				FolioNumber,
				MISTABLE.DateStamp,
				SegmentNumber,
				PointOfSaleNumber,
				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
		   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
				   ))

	    PRINT 'VatOfPriceCur ready'
            RAISERROR(N'', 0, 1) WITH NOWAIT
              
	    OPEN VatOfPriceCur;
	    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, @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;
	    WHILE(@@FETCH_STATUS <> -1)
	    BEGIN
        --if IsNull(@RoomTypeNumber, -1) = -1
        --Begin
        --  Print '@RoomTypeNumber er NULL, ReferenceNumber=' + convert(varchar, @ReferenceNumber) + ', @DateStamp=' + @DateStamp
        --  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
		 BEGIN
		   SET @BookedVatOfPrice = 0;
		 END;
		 INSERT INTO MISTABLE
		 (Room_HallType,
		  ReferenceNumber,
		  GuestNumber,
		  FolioNumber,
		  DateStamp,
		  SegmentNumber,
		  PointOfSaleNumber,
		  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
		 )
		 VALUES
		 (@Room_HallType,
		  @ReferenceNumber,
		  @GuestNumber,
		  @FolioNumber,
		  @DateStamp,
		  @SegmentNumber,
		  @PointOfSaleNumber,
		  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
		 );
		 FETCH NEXT FROM VatOfPriceCur INTO @Room_HallType, @ReferenceNumber, @GuestNumber, @FolioNumber, @DateStamp, @SegmentNumber, @PointOfSaleNumber, @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;
	    END;

	    CLOSE VatOfPriceCur;
	    DEALLOCATE VatOfPriceCur;
--     End -- @CalcMISFromDate = ''

     DROP TABLE #ReservationsCrossDate;
     DROP TABLE #FoliosCrossDate;
     DROP TABLE #ResToRecalc;
     DROP TABLE #PacketInfo
     DECLARE @StartDate DATETIME;
     SET @StartDate = CONVERT(DATETIME, @FormatedStartDate);
     EXEC GenerateMISTotals
          @StartDate;
     UPDATE HotelSetup set KeyValue = 0 Where Searchkey = 'MISCalcRunning';
     
	 