Diff
Not logged in

Differences From Artifact [a2babe2b20]:

To Artifact [183c81977c]:


85
86
87
88
89
90
91
92
93


94
95
96
97
98
99
100
101
102
103
104
105
106
107










108
109
110

111
112
113

114
115
116


117
118
119
120
121
122
123

124
125
126
127
128
129
130
131
132
133
134
135
136

137
138
139
140
141
142
143
85
86
87
88
89
90
91


92
93

94
95
96










97
98
99
100
101
102
103
104
105
106

107

108

109

110



111
112

113
114
115
116


117
118
119
120
121
122
123
124
125
126
127
128
129

130
131
132
133
134
135
136
137







-
-
+
+
-



-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-

-
+
-

-
+
-
-
-
+
+
-




-
-
+












-
+







			    TclDateFields *, int);
static int		ClockConfigureObjCmd(void *clientData,
			    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]);
static void		GetYearWeekDay(TclDateFields *, int);
static void		GetGregorianEraYearDay(TclDateFields *, int);
static void		GetMonthDay(TclDateFields *);
static Tcl_WideInt	WeekdayOnOrBefore(int, Tcl_WideInt);
static Tcl_ObjCmdProc ClockClicksObjCmd;
static Tcl_ObjCmdProc ClockConvertlocaltoutcObjCmd;
static Tcl_ObjCmdProc	ClockClicksObjCmd;
static Tcl_ObjCmdProc	ClockConvertlocaltoutcObjCmd;

static int		ClockGetDateFields(void *clientData,
			    Tcl_Interp *interp, TclDateFields *fields,
			    Tcl_Obj *timezoneObj, int changeover);
static Tcl_ObjCmdProc ClockGetdatefieldsObjCmd;
static Tcl_ObjCmdProc ClockGetjuliandayfromerayearmonthdayObjCmd;
static Tcl_ObjCmdProc ClockGetjuliandayfromerayearweekdayObjCmd;
static Tcl_ObjCmdProc ClockGetenvObjCmd;
static Tcl_ObjCmdProc ClockMicrosecondsObjCmd;
static Tcl_ObjCmdProc ClockMillisecondsObjCmd;
static Tcl_ObjCmdProc ClockSecondsObjCmd;
static Tcl_ObjCmdProc ClockFormatObjCmd;
static Tcl_ObjCmdProc ClockScanObjCmd;
static int		ClockScanCommit(
static Tcl_ObjCmdProc	ClockGetdatefieldsObjCmd;
static Tcl_ObjCmdProc	ClockGetjuliandayfromerayearmonthdayObjCmd;
static Tcl_ObjCmdProc	ClockGetjuliandayfromerayearweekdayObjCmd;
static Tcl_ObjCmdProc	ClockGetenvObjCmd;
static Tcl_ObjCmdProc	ClockMicrosecondsObjCmd;
static Tcl_ObjCmdProc	ClockMillisecondsObjCmd;
static Tcl_ObjCmdProc	ClockSecondsObjCmd;
static Tcl_ObjCmdProc	ClockFormatObjCmd;
static Tcl_ObjCmdProc	ClockScanObjCmd;
static int		ClockScanCommit(DateInfo *info,
			    DateInfo *info,
			    ClockFmtScnCmdArgs *opts);
static int		ClockFreeScan(
static int		ClockFreeScan(DateInfo *info,
			    DateInfo *info,
			    Tcl_Obj *strObj, ClockFmtScnCmdArgs *opts);
static int		ClockCalcRelTime(
static int		ClockCalcRelTime(DateInfo *info);
			    DateInfo *info);
static Tcl_ObjCmdProc ClockAddObjCmd;
static int		ClockValidDate(
static Tcl_ObjCmdProc	ClockAddObjCmd;
static int		ClockValidDate(DateInfo *,
			    DateInfo *,
			    ClockFmtScnCmdArgs *, int stage);
static struct tm *	ThreadSafeLocalTime(const time_t *);
static size_t		TzsetIfNecessary(void);
static void		ClockDeleteCmdProc(void *);

static Tcl_ObjCmdProc ClockSafeCatchCmd;
static Tcl_ObjCmdProc	ClockSafeCatchCmd;
/*
 * Structure containing description of "native" clock commands to create.
 */

struct ClockCommand {
    const char *name;		/* The tail of the command name. The full name
				 * is "::tcl::clock::<name>". When NULL marks
				 * the end of the table. */
    Tcl_ObjCmdProc *objCmdProc; /* Function that implements the command. This
				 * will always have the ClockClientData sent
				 * to it, but may well ignore this data. */
    CompileProc *compileProc;	/* The compiler for the command. */
    void *clientData;	/* Any clientData to give the command (if NULL
    void *clientData;		/* Any clientData to give the command (if NULL
    				 * a reference to ClockClientData will be sent) */
};

static const struct ClockCommand clockCommands[] = {
    {"add",		ClockAddObjCmd,		TclCompileBasicMin1ArgCmd, NULL},
    {"clicks",		ClockClicksObjCmd,	TclCompileClockClicksCmd,  NULL},
    {"format",		ClockFormatObjCmd,	TclCompileBasicMin1ArgCmd, NULL},
178
179
180
181
182
183
184
185

186
187
188
189
190
191
192
172
173
174
175
176
177
178

179
180
181
182
183
184
185
186







-
+







TclClockInit(
    Tcl_Interp *interp)		/* Tcl interpreter */
{
    const struct ClockCommand *clockCmdPtr;
    char cmdName[50];		/* Buffer large enough to hold the string
				 *::tcl::clock::GetJulianDayFromEraYearMonthDay
				 * plus a terminating NUL. */
    Command         *cmdPtr;
    Command *cmdPtr;
    ClockClientData *data;
    int i;

    /*
     * Safe interps get [::clock] as alias to a parent, so do not need their
     * own copies of the support routines.
     */
262
263
264
265
266
267
268
269

270
271
272
273
274
275
276
256
257
258
259
260
261
262

263
264
265
266
267
268
269
270







-
+







	}
	cmdPtr = (Command *)Tcl_CreateObjCommand(interp, cmdName,
		clockCmdPtr->objCmdProc, clientData,
		clockCmdPtr->clientData ? NULL : ClockDeleteCmdProc);
	cmdPtr->compileProc = clockCmdPtr->compileProc ?
		clockCmdPtr->compileProc : TclCompileBasicMin0ArgCmd;
    }
    cmdPtr = (Command *)Tcl_CreateObjCommand(interp,
    cmdPtr = (Command *) Tcl_CreateObjCommand(interp,
	    "::tcl::unsupported::clock::configure",
	    ClockConfigureObjCmd, data, ClockDeleteCmdProc);
    data->refCount++;
    cmdPtr->compileProc = TclCompileBasicMin0ArgCmd;
}

/*
415
416
417
418
419
420
421
422
423


424
425
426
427
428
429


430
431
432
433
434


435
436
437
438
439

440
441
442
443
444
445
446




447
448
449
450
451
452
453


454
455
456
457
458
459


460
461
462
463
464
465


466
467
468
469
470
471
472
473
409
410
411
412
413
414
415


416
417
418
419
420
421


422
423

424
425


426
427

428
429
430

431

432
433




434
435
436
437

438
439
440
441


442
443

444
445
446


447
448

449
450
451


452
453

454
455
456
457
458
459
460







-
-
+
+




-
-
+
+
-


-
-
+
+
-



-
+
-


-
-
-
-
+
+
+
+
-




-
-
+
+
-



-
-
+
+
-



-
-
+
+
-







 *
 *----------------------------------------------------------------------
 */

static Tcl_Obj *
NormTimezoneObj(
    ClockClientData *dataPtr,	/* Client data containing literal pool */
    Tcl_Obj	*timezoneObj,	/* Name of zone to find */
    int		*loaded)	/* Used to recognized TZ was loaded */
    Tcl_Obj *timezoneObj,	/* Name of zone to find */
    int *loaded)		/* Used to recognized TZ was loaded */
{
    const char *tz;

    *loaded = 1;
    if ( timezoneObj == dataPtr->lastSetupTimeZoneUnnorm
      && dataPtr->lastSetupTimeZone != NULL
    if (timezoneObj == dataPtr->lastSetupTimeZoneUnnorm
	    && dataPtr->lastSetupTimeZone != NULL) {
    ) {
	return dataPtr->lastSetupTimeZone;
    }
    if ( timezoneObj == dataPtr->prevSetupTimeZoneUnnorm
      && dataPtr->prevSetupTimeZone != NULL
    if (timezoneObj == dataPtr->prevSetupTimeZoneUnnorm
	    && dataPtr->prevSetupTimeZone != NULL) {
    ) {
    	return dataPtr->prevSetupTimeZone;
    }
    if (timezoneObj == dataPtr->gmtSetupTimeZoneUnnorm
      && dataPtr->gmtSetupTimeZone != NULL
	    && dataPtr->gmtSetupTimeZone != NULL) {
    ) {
	return dataPtr->literals[LIT_GMT];
    }
    if ( timezoneObj == dataPtr->lastSetupTimeZone
      || timezoneObj == dataPtr->prevSetupTimeZone
      || timezoneObj == dataPtr->gmtSetupTimeZone
      || timezoneObj == dataPtr->systemTimeZone
    if (timezoneObj == dataPtr->lastSetupTimeZone
	    || timezoneObj == dataPtr->prevSetupTimeZone
	    || timezoneObj == dataPtr->gmtSetupTimeZone
	    || timezoneObj == dataPtr->systemTimeZone) {
    ) {
	return timezoneObj;
    }

    tz = TclGetString(timezoneObj);
    if (dataPtr->lastSetupTimeZone != NULL &&
	strcmp(tz, TclGetString(dataPtr->lastSetupTimeZone)) == 0
    if (dataPtr->lastSetupTimeZone != NULL
	    && strcmp(tz, TclGetString(dataPtr->lastSetupTimeZone)) == 0) {
    ) {
	TclSetObjRef(dataPtr->lastSetupTimeZoneUnnorm, timezoneObj);
	return dataPtr->lastSetupTimeZone;
    }
    if (dataPtr->prevSetupTimeZone != NULL &&
	strcmp(tz, TclGetString(dataPtr->prevSetupTimeZone)) == 0
    if (dataPtr->prevSetupTimeZone != NULL
	    && strcmp(tz, TclGetString(dataPtr->prevSetupTimeZone)) == 0) {
    ) {
	TclSetObjRef(dataPtr->prevSetupTimeZoneUnnorm, timezoneObj);
	return dataPtr->prevSetupTimeZone;
    }
    if (dataPtr->systemTimeZone != NULL &&
	strcmp(tz, TclGetString(dataPtr->systemTimeZone)) == 0
    if (dataPtr->systemTimeZone != NULL
	    && strcmp(tz, TclGetString(dataPtr->systemTimeZone)) == 0) {
    ) {
	return dataPtr->systemTimeZone;
    }
    if (strcmp(tz, Literals[LIT_GMT]) == 0) {
	TclSetObjRef(dataPtr->gmtSetupTimeZoneUnnorm, timezoneObj);
	if (dataPtr->gmtSetupTimeZone == NULL) {
	    *loaded = 0;
	}
551
552
553
554
555
556
557

558
559
560
561
562
563
564
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552







+







 */

static inline void
SavePrevLocaleObj(
    ClockClientData *dataPtr)	/* Client data containing literal pool */
{
    Tcl_Obj *localeObj = dataPtr->lastUsedLocale;

    if (localeObj && localeObj != dataPtr->prevUsedLocale) {
	TclSetObjRef(dataPtr->prevUsedLocaleUnnorm, dataPtr->lastUsedLocaleUnnorm);
	TclSetObjRef(dataPtr->prevUsedLocale, localeObj);
	/* mcDicts owns reference to dict */
	dataPtr->prevUsedLocaleDict = dataPtr->lastUsedLocaleDict;
    }
}
579
580
581
582
583
584
585
586
587


588
589

590
591
592



593
594
595
596

597

598
599


600
601
602
603
604
605
606

607
608


609
610
611
612

613
614


615
616
617
618
619
620
621
622
623
624




625
626
627
628
629
630

631
632
633
634




635
636
637
638
639
640
641

642
643
644
645




646
647
648
649
650
651
652
653
654
655
656
657
658






659
660
661
662

663

664
665


666
667
668
669
670
671
672
673
674
675



676
677
678
679
680
681
682
683

684
685
686
687
688
689
690
567
568
569
570
571
572
573


574
575
576
577
578



579
580
581

582
583

584
585
586


587
588

589
590
591
592
593
594
595


596
597

598
599
600
601


602
603

604
605
606
607
608




609
610
611
612



613
614
615
616




617
618
619
620



621
622
623
624
625




626
627
628
629



630
631
632
633






634
635
636
637
638
639

640
641

642
643
644


645
646

647
648
649
650
651
652



653
654
655

656
657
658
659
660
661
662
663
664
665
666
667
668
669
670







-
-
+
+


+
-
-
-
+
+
+
-


-
+

+
-
-
+
+
-






+
-
-
+
+
-



+
-
-
+
+
-





-
-
-
-
+
+
+
+
-
-
-



+
-
-
-
-
+
+
+
+
-
-
-




+
-
-
-
-
+
+
+
+
-
-
-




-
-
-
-
-
-
+
+
+
+
+
+
-


-
+

+
-
-
+
+
-






-
-
-
+
+
+
-







+







 *----------------------------------------------------------------------
 */

static Tcl_Obj *
NormLocaleObj(
    ClockClientData *dataPtr,	/* Client data containing literal pool */
    Tcl_Interp *interp,		/* Tcl interpreter */
    Tcl_Obj    *localeObj,
    Tcl_Obj   **mcDictObj)
    Tcl_Obj *localeObj,
    Tcl_Obj **mcDictObj)
{
    const char *loc, *loc2;

    if ( localeObj == NULL
      || localeObj == dataPtr->literals[LIT_C]
      || localeObj == dataPtr->defaultLocale
    if (localeObj == NULL
	    || localeObj == dataPtr->literals[LIT_C]
	    || localeObj == dataPtr->defaultLocale) {
    ) {
	*mcDictObj = dataPtr->defaultLocaleDict;
	return dataPtr->defaultLocale ?
		    dataPtr->defaultLocale : dataPtr->literals[LIT_C];
		dataPtr->defaultLocale : dataPtr->literals[LIT_C];
    }

    if ( localeObj == dataPtr->currentLocale
      || localeObj == dataPtr->literals[LIT_CURRENT]
    if (localeObj == dataPtr->currentLocale
	    || localeObj == dataPtr->literals[LIT_CURRENT]) {
    ) {
	if (dataPtr->currentLocale == NULL) {
	    ClockGetCurrentLocale(dataPtr, interp);
	}
	*mcDictObj = dataPtr->currentLocaleDict;
	return dataPtr->currentLocale;
    }

    if ( localeObj == dataPtr->lastUsedLocale
      || localeObj == dataPtr->lastUsedLocaleUnnorm
    if (localeObj == dataPtr->lastUsedLocale
	    || localeObj == dataPtr->lastUsedLocaleUnnorm) {
    ) {
	*mcDictObj = dataPtr->lastUsedLocaleDict;
	return dataPtr->lastUsedLocale;
    }

    if ( localeObj == dataPtr->prevUsedLocale
      || localeObj == dataPtr->prevUsedLocaleUnnorm
    if (localeObj == dataPtr->prevUsedLocale
	    || localeObj == dataPtr->prevUsedLocaleUnnorm) {
    ) {
	*mcDictObj = dataPtr->prevUsedLocaleDict;
	return dataPtr->prevUsedLocale;
    }

    loc = TclGetString(localeObj);
    if ( dataPtr->currentLocale != NULL
      && ( localeObj == dataPtr->currentLocale
       || (localeObj->length == dataPtr->currentLocale->length
	  && strcasecmp(loc, TclGetString(dataPtr->currentLocale)) == 0
    if (dataPtr->currentLocale != NULL
	    && (localeObj == dataPtr->currentLocale
	    || (localeObj->length == dataPtr->currentLocale->length
	    && strcasecmp(loc, TclGetString(dataPtr->currentLocale)) == 0))) {
	)
      )
    ) {
	*mcDictObj = dataPtr->currentLocaleDict;
	return dataPtr->currentLocale;
    }

    if ( dataPtr->lastUsedLocale != NULL
      && ( localeObj == dataPtr->lastUsedLocale
       || (localeObj->length == dataPtr->lastUsedLocale->length
	  && strcasecmp(loc, TclGetString(dataPtr->lastUsedLocale)) == 0
    if (dataPtr->lastUsedLocale != NULL
	    && (localeObj == dataPtr->lastUsedLocale
	    || (localeObj->length == dataPtr->lastUsedLocale->length
	    && strcasecmp(loc, TclGetString(dataPtr->lastUsedLocale)) == 0))) {
	)
      )
    ) {
	*mcDictObj = dataPtr->lastUsedLocaleDict;
	TclSetObjRef(dataPtr->lastUsedLocaleUnnorm, localeObj);
	return dataPtr->lastUsedLocale;
    }

    if ( dataPtr->prevUsedLocale != NULL
      && ( localeObj == dataPtr->prevUsedLocale
       || (localeObj->length == dataPtr->prevUsedLocale->length
	  && strcasecmp(loc, TclGetString(dataPtr->prevUsedLocale)) == 0
    if (dataPtr->prevUsedLocale != NULL
	    && (localeObj == dataPtr->prevUsedLocale
	    || (localeObj->length == dataPtr->prevUsedLocale->length
	    && strcasecmp(loc, TclGetString(dataPtr->prevUsedLocale)) == 0))) {
	)
      )
    ) {
	*mcDictObj = dataPtr->prevUsedLocaleDict;
	TclSetObjRef(dataPtr->prevUsedLocaleUnnorm, localeObj);
	return dataPtr->prevUsedLocale;
    }
    if (
	 (localeObj->length == 1 /* C */
	   && strcasecmp(loc, Literals[LIT_C]) == 0)
      || (dataPtr->defaultLocale && (loc2 = TclGetString(dataPtr->defaultLocale))
      	   && localeObj->length == dataPtr->defaultLocale->length
	   && strcasecmp(loc, loc2) == 0)

    if ((localeObj->length == 1 /* C */
	    && strcasecmp(loc, Literals[LIT_C]) == 0)
	    || (dataPtr->defaultLocale && (loc2 = TclGetString(dataPtr->defaultLocale))
      	    && localeObj->length == dataPtr->defaultLocale->length
	    && strcasecmp(loc, loc2) == 0)) {
    ) {
	*mcDictObj = dataPtr->defaultLocaleDict;
	return dataPtr->defaultLocale ?
		    dataPtr->defaultLocale : dataPtr->literals[LIT_C];
		dataPtr->defaultLocale : dataPtr->literals[LIT_C];
    }

    if ( localeObj->length == 7 /* current */
      && strcasecmp(loc, Literals[LIT_CURRENT]) == 0
    if (localeObj->length == 7 /* current */
	    && strcasecmp(loc, Literals[LIT_CURRENT]) == 0) {
    ) {
	if (dataPtr->currentLocale == NULL) {
	    ClockGetCurrentLocale(dataPtr, interp);
	}
	*mcDictObj = dataPtr->currentLocaleDict;
	return dataPtr->currentLocale;
    }
    if (
	 (localeObj->length == 6 /* system */
	   && strcasecmp(loc, Literals[LIT_SYSTEM]) == 0)

    if ((localeObj->length == 6 /* system */
	    && strcasecmp(loc, Literals[LIT_SYSTEM]) == 0)) {
    ) {
	SavePrevLocaleObj(dataPtr);
	TclSetObjRef(dataPtr->lastUsedLocaleUnnorm, localeObj);
	localeObj = ClockGetSystemLocale(dataPtr, interp);
	TclSetObjRef(dataPtr->lastUsedLocale, localeObj);
	*mcDictObj = NULL;
	return localeObj;
    }

    *mcDictObj = NULL;
    return localeObj;
}

/*
 *----------------------------------------------------------------------
 *
699
700
701
702
703
704
705

706

707
708
709
710
711
712
713
714

715
716
717


718
719
720
721


722
723
724
725
726
727
728
729

730


731
732
733

734
735
736
737
738
739
740
741
742
743
744
745
746
747

748
749
750
751
752
753
754
679
680
681
682
683
684
685
686

687
688
689
690
691
692
693
694

695



696
697
698
699


700
701
702
703
704
705
706
707
708
709
710

711
712
713
714

715
716
717
718
719
720
721
722
723
724
725
726
727
728

729
730
731
732
733
734
735
736







+
-
+







-
+
-
-
-
+
+


-
-
+
+








+
-
+
+


-
+













-
+







 * Results:
 *	Tcl-object contains smart reference to msgcat dictionary.
 *
 *----------------------------------------------------------------------
 */

Tcl_Obj *
ClockMCDict(
ClockMCDict(ClockFmtScnCmdArgs *opts)
    ClockFmtScnCmdArgs *opts)
{
    ClockClientData *dataPtr = (ClockClientData *)opts->clientData;

    /* if dict not yet retrieved */
    if (opts->mcDictObj == NULL) {

	/* if locale was not yet used */
	if ( !(opts->flags & CLF_LOCALE_USED) ) {
	if (!(opts->flags & CLF_LOCALE_USED)) {

	    opts->localeObj = NormLocaleObj((ClockClientData *)opts->clientData, opts->interp,
		opts->localeObj, &opts->mcDictObj);
	    opts->localeObj = NormLocaleObj((ClockClientData *) opts->clientData, opts->interp,
		    opts->localeObj, &opts->mcDictObj);

	    if (opts->localeObj == NULL) {
		Tcl_SetObjResult(opts->interp,
		    Tcl_NewStringObj("locale not specified and no default locale set", -1));
		Tcl_SetObjResult(opts->interp, Tcl_NewStringObj(
			"locale not specified and no default locale set", -1));
		Tcl_SetErrorCode(opts->interp, "CLOCK", "badOption", (char *)NULL);
		return NULL;
	    }
	    opts->flags |= CLF_LOCALE_USED;

	    /* check locale literals already available (on demand creation) */
	    if (dataPtr->mcLiterals == NULL) {
		int i;

		dataPtr->mcLiterals = (Tcl_Obj **)Tcl_Alloc(MCLIT__END * sizeof(Tcl_Obj*));
		dataPtr->mcLiterals = (Tcl_Obj **)
			Tcl_Alloc(MCLIT__END * sizeof(Tcl_Obj*));
		for (i = 0; i < MCLIT__END; ++i) {
		    TclInitObjRef(dataPtr->mcLiterals[i],
			Tcl_NewStringObj(MsgCtLiterals[i], -1));
			    Tcl_NewStringObj(MsgCtLiterals[i], -1));
		}
	    }
	}

	/* check or obtain mcDictObj (be sure it's modifiable) */
	if (opts->mcDictObj == NULL || opts->mcDictObj->refCount > 1) {
	    int ref = 1;

	    /* first try to find locale catalog dict */
	    if (dataPtr->mcDicts == NULL) {
		TclSetObjRef(dataPtr->mcDicts, Tcl_NewDictObj());
	    }
	    Tcl_DictObjGet(NULL, dataPtr->mcDicts,
		opts->localeObj, &opts->mcDictObj);
		    opts->localeObj, &opts->mcDictObj);

	    if (opts->mcDictObj == NULL) {
		/* get msgcat dictionary - ::tcl::clock::mcget locale */
		Tcl_Obj *callargs[2];

		callargs[0] = dataPtr->literals[LIT_MCGET];
		callargs[1] = opts->localeObj;
762
763
764
765
766
767
768
769

770
771
772
773
774

775
776
777


778
779
780
781

782
783

784
785
786
787
788
789
790
744
745
746
747
748
749
750

751
752
753
754
755

756
757


758
759

760
761

762
763

764
765
766
767
768
769
770
771







-
+




-
+

-
-
+
+
-


-
+

-
+







		ref = 0; /* new object is not yet referenced */
	    }

	    /* be sure that object reference doesn't increase (dict changeable) */
	    if (opts->mcDictObj->refCount > ref) {
		/* smart reference (shared dict as object with no ref-counter) */
		opts->mcDictObj = TclDictObjSmartRef(opts->interp,
		    opts->mcDictObj);
			opts->mcDictObj);
	    }

	    /* create exactly one reference to catalog / make it searchable for future */
	    Tcl_DictObjPut(NULL, dataPtr->mcDicts, opts->localeObj,
		opts->mcDictObj);
		    opts->mcDictObj);

	    if ( opts->localeObj == dataPtr->literals[LIT_C]
	      || opts->localeObj == dataPtr->defaultLocale
	    if (opts->localeObj == dataPtr->literals[LIT_C]
		    || opts->localeObj == dataPtr->defaultLocale) {
	    ) {
		dataPtr->defaultLocaleDict = opts->mcDictObj;
	    }
	    if ( opts->localeObj == dataPtr->currentLocale ) {
	    if (opts->localeObj == dataPtr->currentLocale) {
		dataPtr->currentLocaleDict = opts->mcDictObj;
	    } else if ( opts->localeObj == dataPtr->lastUsedLocale ) {
	    } else if (opts->localeObj == dataPtr->lastUsedLocale) {
		dataPtr->lastUsedLocaleDict = opts->mcDictObj;
	    } else {
		SavePrevLocaleObj(dataPtr);
		TclSetObjRef(dataPtr->lastUsedLocale, opts->localeObj);
		TclUnsetObjRef(dataPtr->lastUsedLocaleUnnorm);
		dataPtr->lastUsedLocaleDict = opts->mcDictObj;
	    }
811
812
813
814
815
816
817
818
819
820
821
822
823

824

825
826
827
828

829
830
831
832
833
834
835
792
793
794
795
796
797
798

799
800
801
802

803
804
805
806
807
808

809
810
811
812
813
814
815
816







-




-
+

+



-
+








Tcl_Obj *
ClockMCGet(
    ClockFmtScnCmdArgs *opts,
    int mcKey)
{
    ClockClientData *dataPtr = (ClockClientData *)opts->clientData;

    Tcl_Obj *valObj = NULL;

    if (opts->mcDictObj == NULL) {
	ClockMCDict(opts);
	if (opts->mcDictObj == NULL)
	if (opts->mcDictObj == NULL) {
	    return NULL;
	}
    }

    Tcl_DictObjGet(opts->interp, opts->mcDictObj,
	dataPtr->mcLiterals[mcKey], &valObj);
	    dataPtr->mcLiterals[mcKey], &valObj);

    return valObj; /* or NULL in obscure case if Tcl_DictObjGet failed */
}

/*
 *----------------------------------------------------------------------
 *
847
848
849
850
851
852
853
854
855
856
857
858
859

860

861
862
863
864
865
866
867
868
869

870
871
872
873
874
875
876
877
878
879
880
828
829
830
831
832
833
834

835
836
837
838

839
840
841
842
843
844
845
846
847
848
849

850

851
852

853
854
855
856
857
858
859







-




-
+

+








-
+
-


-








MODULE_SCOPE Tcl_Obj *
ClockMCGetIdx(
    ClockFmtScnCmdArgs *opts,
    int mcKey)
{
    ClockClientData *dataPtr = (ClockClientData *)opts->clientData;

    Tcl_Obj *valObj = NULL;

    if (opts->mcDictObj == NULL) {
	ClockMCDict(opts);
	if (opts->mcDictObj == NULL)
	if (opts->mcDictObj == NULL) {
	    return NULL;
	}
    }

    /* try to get indices object */
    if (dataPtr->mcLitIdxs == NULL) {
	return NULL;
    }

    if (Tcl_DictObjGet(NULL, opts->mcDictObj,
	dataPtr->mcLitIdxs[mcKey], &valObj) != TCL_OK
	    dataPtr->mcLitIdxs[mcKey], &valObj) != TCL_OK) {
    ) {
	return NULL;
    }

    return valObj;
}

/*
 *----------------------------------------------------------------------
 *
 * ClockMCSetIdx --
888
889
890
891
892
893
894
895


896
897
898
899
900
901

902

903
904
905
906
907

908
909
910
911

912
913
914
915
916
917
918
919
920
921
922
923


924
925
926
927
928
929
930
867
868
869
870
871
872
873

874
875
876
877
878
879
880

881
882
883
884
885
886
887
888
889
890
891
892

893
894
895
896
897
898
899
900
901
902
903


904
905
906
907
908
909
910
911
912







-
+
+





-
+

+





+



-
+










-
-
+
+







 *
 *----------------------------------------------------------------------
 */

int
ClockMCSetIdx(
    ClockFmtScnCmdArgs *opts,
    int mcKey, Tcl_Obj *valObj)
    int mcKey,
    Tcl_Obj *valObj)
{
    ClockClientData *dataPtr = (ClockClientData *)opts->clientData;

    if (opts->mcDictObj == NULL) {
	ClockMCDict(opts);
	if (opts->mcDictObj == NULL)
	if (opts->mcDictObj == NULL) {
	    return TCL_ERROR;
	}
    }

    /* if literal storage for indices not yet created */
    if (dataPtr->mcLitIdxs == NULL) {
	int i;

	dataPtr->mcLitIdxs = (Tcl_Obj **)Tcl_Alloc(MCLIT__END * sizeof(Tcl_Obj*));
	for (i = 0; i < MCLIT__END; ++i) {
	    TclInitObjRef(dataPtr->mcLitIdxs[i],
		Tcl_NewStringObj(MsgCtLitIdxs[i], -1));
		    Tcl_NewStringObj(MsgCtLitIdxs[i], -1));
	}
    }

    return Tcl_DictObjPut(opts->interp, opts->mcDictObj,
	    dataPtr->mcLitIdxs[mcKey], valObj);
}

static void
TimezoneLoaded(
    ClockClientData *dataPtr,
    Tcl_Obj	*timezoneObj,	/* Name of zone was loaded */
    Tcl_Obj	*tzUnnormObj)	/* Name of zone was loaded */
    Tcl_Obj *timezoneObj,	/* Name of zone was loaded */
    Tcl_Obj *tzUnnormObj)	/* Name of zone was loaded */
{
    /* don't overwrite last-setup with GMT (special case) */
    if (timezoneObj == dataPtr->literals[LIT_GMT]) {
	/* mark GMT zone loaded */
	if (dataPtr->gmtSetupTimeZone == NULL) {
	    TclSetObjRef(dataPtr->gmtSetupTimeZone,
		dataPtr->literals[LIT_GMT]);
958
959
960
961
962
963
964
965
966
967
968




969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992

993
994

995
996
997
998
999
1000

1001
1002
1003
1004
1005
1006
1007
1008
1009


1010
1011
1012
1013


1014
1015
1016
1017

1018
1019
1020
1021
1022
1023
1024

1025
1026
1027

1028
1029
1030
1031
1032
1033
1034
1035

1036
1037

1038
1039

1040
1041
1042
1043
1044
1045
1046
1047

1048
1049
1050

1051
1052
1053

1054
1055
1056
1057
1058

1059
1060
1061
1062
1063

1064
1065

1066
1067

1068
1069
1070

1071
1072
1073
1074
1075
1076
1077
1078

1079
1080

1081
1082

1083
1084
1085

1086
1087
1088
1089
1090
1091
1092
1093

1094
1095

1096
1097

1098
1099
1100

1101
1102
1103
1104
1105
1106
1107
1108

1109
1110

1111
1112

1113
1114
1115

1116
1117
1118
1119
1120
1121
1122
1123
1124


1125
1126
1127

1128
1129
1130

1131
1132
1133
1134
1135
1136
1137
1138
1139
1140

1141
1142
1143
1144

1145
1146
1147
1148


1149
1150
1151
1152
1153
1154





1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166











1167
1168


1169
1170
1171
1172
1173
1174
1175
940
941
942
943
944
945
946




947
948
949
950
951
952

953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972

973
974

975
976
977
978
979
980
981
982
983
984
985
986
987
988
989


990
991
992
993


994
995
996
997
998
999
1000
1001
1002
1003
1004



1005
1006
1007

1008
1009
1010
1011
1012
1013
1014
1015

1016
1017

1018
1019

1020
1021
1022
1023
1024
1025
1026
1027

1028
1029
1030

1031
1032
1033
1034
1035
1036
1037
1038
1039

1040
1041
1042
1043
1044

1045
1046

1047
1048

1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060

1061
1062

1063
1064

1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076

1077
1078

1079
1080

1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092

1093
1094

1095
1096

1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108


1109
1110

1111

1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125

1126
1127
1128
1129

1130
1131
1132


1133
1134






1135
1136
1137
1138
1139
1140











1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151


1152
1153
1154
1155
1156
1157
1158
1159
1160







-
-
-
-
+
+
+
+


-




















-
+

-
+






+







-
-
+
+


-
-
+
+




+




-
-
-
+


-
+







-
+

-
+

-
+







-
+


-
+



+




-
+




-
+

-
+

-
+



+







-
+

-
+

-
+



+







-
+

-
+

-
+



+







-
+

-
+

-
+



+







-
-
+
+
-

-
+



+









-
+



-
+


-
-
+
+
-
-
-
-
-
-
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+







 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
ClockConfigureObjCmd(
    void *clientData,  /* Client data containing literal pool */
    Tcl_Interp *interp,	    /* Tcl interpreter */
    int objc,		    /* Parameter count */
    Tcl_Obj *const objv[])  /* Parameter vector */
    void *clientData,		/* Client data containing literal pool */
    Tcl_Interp *interp,		/* Tcl interpreter */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[])	/* Parameter vector */
{
    ClockClientData *dataPtr = (ClockClientData *)clientData;

    static const char *const options[] = {
	"-system-tz",	  "-setup-tz",	  "-default-locale",	"-current-locale",
	"-clear",
	"-year-century",  "-century-switch",
	"-min-year", "-max-year", "-max-jdn", "-validate",
	"-init-complete",
	NULL
    };
    enum optionInd {
	CLOCK_SYSTEM_TZ,  CLOCK_SETUP_TZ, CLOCK_DEFAULT_LOCALE, CLOCK_CURRENT_LOCALE,
	CLOCK_CLEAR_CACHE,
	CLOCK_YEAR_CENTURY, CLOCK_CENTURY_SWITCH,
	CLOCK_MIN_YEAR, CLOCK_MAX_YEAR, CLOCK_MAX_JDN, CLOCK_VALIDATE,
	CLOCK_INIT_COMPLETE
    };
    int optionIndex;		/* Index of an option. */
    int i;

    for (i = 1; i < objc; i++) {
	if (Tcl_GetIndexFromObj(interp, objv[i++], options,
	    "option", 0, &optionIndex) != TCL_OK) {
		"option", 0, &optionIndex) != TCL_OK) {
	    Tcl_SetErrorCode(interp, "CLOCK", "badOption",
		    TclGetString(objv[i-1]), (char *)NULL);
		    TclGetString(objv[i - 1]), (char *)NULL);
	    return TCL_ERROR;
	}
	switch (optionIndex) {
	case CLOCK_SYSTEM_TZ: {
	    /* validate current tz-epoch */
	    size_t lastTZEpoch = TzsetIfNecessary();

	    if (i < objc) {
		if (dataPtr->systemTimeZone != objv[i]) {
		    TclSetObjRef(dataPtr->systemTimeZone, objv[i]);
		    TclUnsetObjRef(dataPtr->systemSetupTZData);
		}
		dataPtr->lastTZEpoch = lastTZEpoch;
	    }
	    if (i+1 >= objc && dataPtr->systemTimeZone != NULL
			 && dataPtr->lastTZEpoch == lastTZEpoch) {
	    if (i + 1 >= objc && dataPtr->systemTimeZone != NULL
		    && dataPtr->lastTZEpoch == lastTZEpoch) {
		Tcl_SetObjResult(interp, dataPtr->systemTimeZone);
	    }
	}
	break;
	    break;
	}
	case CLOCK_SETUP_TZ:
	    if (i < objc) {
		int loaded;
		Tcl_Obj *timezoneObj = NormTimezoneObj(dataPtr, objv[i], &loaded);

		if (!loaded) {
		    TimezoneLoaded(dataPtr, timezoneObj, objv[i]);
		}
		Tcl_SetObjResult(interp, timezoneObj);
	    }
	    else
	    if (i+1 >= objc && dataPtr->lastSetupTimeZone != NULL) {
	    } else if (i + 1 >= objc && dataPtr->lastSetupTimeZone != NULL) {
		Tcl_SetObjResult(interp, dataPtr->lastSetupTimeZone);
	    }
	break;
	    break;
	case CLOCK_DEFAULT_LOCALE:
	    if (i < objc) {
		if (dataPtr->defaultLocale != objv[i]) {
		    TclSetObjRef(dataPtr->defaultLocale, objv[i]);
		    dataPtr->defaultLocaleDict = NULL;
		}
	    }
	    if (i+1 >= objc) {
	    if (i + 1 >= objc) {
		Tcl_SetObjResult(interp, dataPtr->defaultLocale ?
		    dataPtr->defaultLocale : dataPtr->literals[LIT_C]);
			dataPtr->defaultLocale : dataPtr->literals[LIT_C]);
	    }
	break;
	    break;
	case CLOCK_CURRENT_LOCALE:
	    if (i < objc) {
		if (dataPtr->currentLocale != objv[i]) {
		    TclSetObjRef(dataPtr->currentLocale, objv[i]);
		    dataPtr->currentLocaleDict = NULL;
		}
	    }
	    if (i+1 >= objc && dataPtr->currentLocale != NULL) {
	    if (i + 1 >= objc && dataPtr->currentLocale != NULL) {
		Tcl_SetObjResult(interp, dataPtr->currentLocale);
	    }
	break;
	    break;
	case CLOCK_YEAR_CENTURY:
	    if (i < objc) {
		int year;

		if (TclGetIntFromObj(interp, objv[i], &year) != TCL_OK) {
		    return TCL_ERROR;
		}
		dataPtr->currentYearCentury = year;
		if (i+1 >= objc) {
		if (i + 1 >= objc) {
		    Tcl_SetObjResult(interp, objv[i]);
		}
		continue;
	    }
	    if (i+1 >= objc) {
	    if (i + 1 >= objc) {
		Tcl_SetObjResult(interp,
		    Tcl_NewWideIntObj(dataPtr->currentYearCentury));
			Tcl_NewWideIntObj(dataPtr->currentYearCentury));
	    }
	break;
	    break;
	case CLOCK_CENTURY_SWITCH:
	    if (i < objc) {
		int year;

		if (TclGetIntFromObj(interp, objv[i], &year) != TCL_OK) {
		    return TCL_ERROR;
		}
		dataPtr->yearOfCenturySwitch = year;
		Tcl_SetObjResult(interp, objv[i]);
		continue;
	    }
	    if (i+1 >= objc) {
	    if (i + 1 >= objc) {
		Tcl_SetObjResult(interp,
		    Tcl_NewWideIntObj(dataPtr->yearOfCenturySwitch));
			Tcl_NewWideIntObj(dataPtr->yearOfCenturySwitch));
	    }
	break;
	    break;
	case CLOCK_MIN_YEAR:
	    if (i < objc) {
		int year;

		if (TclGetIntFromObj(interp, objv[i], &year) != TCL_OK) {
		    return TCL_ERROR;
		}
		dataPtr->validMinYear = year;
		Tcl_SetObjResult(interp, objv[i]);
		continue;
	    }
	    if (i+1 >= objc) {
	    if (i + 1 >= objc) {
		Tcl_SetObjResult(interp,
		    Tcl_NewWideIntObj(dataPtr->validMinYear));
			Tcl_NewWideIntObj(dataPtr->validMinYear));
	    }
	break;
	    break;
	case CLOCK_MAX_YEAR:
	    if (i < objc) {
		int year;

		if (TclGetIntFromObj(interp, objv[i], &year) != TCL_OK) {
		    return TCL_ERROR;
		}
		dataPtr->validMaxYear = year;
		Tcl_SetObjResult(interp, objv[i]);
		continue;
	    }
	    if (i+1 >= objc) {
	    if (i + 1 >= objc) {
		Tcl_SetObjResult(interp,
		    Tcl_NewWideIntObj(dataPtr->validMaxYear));
			Tcl_NewWideIntObj(dataPtr->validMaxYear));
	    }
	break;
	    break;
	case CLOCK_MAX_JDN:
	    if (i < objc) {
		double jd;

		if (Tcl_GetDoubleFromObj(interp, objv[i], &jd) != TCL_OK) {
		    return TCL_ERROR;
		}
		dataPtr->maxJDN = jd;
		Tcl_SetObjResult(interp, objv[i]);
		continue;
	    }
	    if (i+1 >= objc) {
		Tcl_SetObjResult(interp,
	    if (i + 1 >= objc) {
		Tcl_SetObjResult(interp, Tcl_NewDoubleObj(dataPtr->maxJDN));
		    Tcl_NewDoubleObj(dataPtr->maxJDN));
	    }
	break;
	    break;
	case CLOCK_VALIDATE:
	    if (i < objc) {
		int val;

		if (Tcl_GetBooleanFromObj(interp, objv[i], &val) != TCL_OK) {
		    return TCL_ERROR;
		}
		if (val) {
		    dataPtr->defFlags |= CLF_VALIDATE;
		} else {
		    dataPtr->defFlags &= ~CLF_VALIDATE;
		}
	    }
	    if (i+1 >= objc) {
	    if (i + 1 >= objc) {
		Tcl_SetObjResult(interp,
			Tcl_NewBooleanObj(dataPtr->defFlags & CLF_VALIDATE));
	    }
	break;
	    break;
	case CLOCK_CLEAR_CACHE:
	    ClockConfigureClear(dataPtr);
	break;
	case CLOCK_INIT_COMPLETE:
	    break;
	case CLOCK_INIT_COMPLETE: {
	    {
		/*
		 * Init completed.
		 * Compile clock ensemble (performance purposes).
		 */
		Tcl_Command token = Tcl_FindCommand(interp, "::clock",
	    /*
	     * Init completed.
	     * Compile clock ensemble (performance purposes).
	     */
	    Tcl_Command token = Tcl_FindCommand(interp, "::clock",
		    NULL, TCL_GLOBAL_ONLY);
		if (!token) {
		    return TCL_ERROR;
		}
		int ensFlags = 0;
		if (Tcl_GetEnsembleFlags(interp, token, &ensFlags) != TCL_OK) {
		    return TCL_ERROR;
		}
		ensFlags |= ENSEMBLE_COMPILE;
		if (Tcl_SetEnsembleFlags(interp, token, ensFlags) != TCL_OK) {
		    return TCL_ERROR;
		}
	    if (!token) {
		return TCL_ERROR;
	    }
	    int ensFlags = 0;
	    if (Tcl_GetEnsembleFlags(interp, token, &ensFlags) != TCL_OK) {
		return TCL_ERROR;
	    }
	    ensFlags |= ENSEMBLE_COMPILE;
	    if (Tcl_SetEnsembleFlags(interp, token, ensFlags) != TCL_OK) {
		return TCL_ERROR;
	    }
	    }
	break;
	    break;
	}
	}
    }

    return TCL_OK;
}

/*
1186
1187
1188
1189
1190
1191
1192
1193

1194
1195
1196
1197
1198
1199
1200
1201
1202


1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220


1221
1222
1223
1224
1225
1226
1227
1228
1229


1230
1231
1232
1233
1234
1235
1236
1237
1238

1239
1240
1241
1242
1243
1244
1245

1246
1247
1248
1249
1250
1251
1252
1171
1172
1173
1174
1175
1176
1177

1178
1179
1180
1181
1182
1183
1184
1185


1186
1187

1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200




1201
1202

1203
1204
1205
1206




1207
1208

1209
1210
1211
1212
1213
1214
1215

1216
1217
1218
1219
1220



1221
1222
1223
1224
1225
1226
1227
1228







-
+







-
-
+
+
-













-
-
-
-
+
+
-




-
-
-
-
+
+
-







-
+




-
-
-
+







 *	The tzdata can be cached in ClockClientData structure.
 *
 *----------------------------------------------------------------------
 */

static inline Tcl_Obj *
ClockGetTZData(
    void *clientData,	/* Opaque pointer to literal pool, etc. */
    void *clientData,		/* Opaque pointer to literal pool, etc. */
    Tcl_Interp *interp,		/* Tcl interpreter */
    Tcl_Obj *timezoneObj)	/* Name of the timezone */
{
    ClockClientData *dataPtr = (ClockClientData *)clientData;
    Tcl_Obj *ret, **out = NULL;

    /* if cached (if already setup this one) */
    if ( timezoneObj == dataPtr->lastSetupTimeZone
      || timezoneObj == dataPtr->lastSetupTimeZoneUnnorm
    if (timezoneObj == dataPtr->lastSetupTimeZone
	    || timezoneObj == dataPtr->lastSetupTimeZoneUnnorm) {
    ) {
	if (dataPtr->lastSetupTZData != NULL) {
	    return dataPtr->lastSetupTZData;
	}
	out = &dataPtr->lastSetupTZData;
    }
    /* differentiate GMT and system zones, because used often */
    /* simple caching, because almost used the tz-data of last timezone
     */
    if (timezoneObj == dataPtr->systemTimeZone) {
	if (dataPtr->systemSetupTZData != NULL) {
	    return dataPtr->systemSetupTZData;
	}
	out = &dataPtr->systemSetupTZData;
    }
    else
    if ( timezoneObj == dataPtr->literals[LIT_GMT]
      || timezoneObj == dataPtr->gmtSetupTimeZoneUnnorm
    } else if (timezoneObj == dataPtr->literals[LIT_GMT]
	    || timezoneObj == dataPtr->gmtSetupTimeZoneUnnorm) {
    ) {
	if (dataPtr->gmtSetupTZData != NULL) {
	    return dataPtr->gmtSetupTZData;
	}
	out = &dataPtr->gmtSetupTZData;
    }
    else
    if ( timezoneObj == dataPtr->prevSetupTimeZone
      || timezoneObj == dataPtr->prevSetupTimeZoneUnnorm
    } else if (timezoneObj == dataPtr->prevSetupTimeZone
	    || timezoneObj == dataPtr->prevSetupTimeZoneUnnorm) {
    ) {
	if (dataPtr->prevSetupTZData != NULL) {
	    return dataPtr->prevSetupTZData;
	}
	out = &dataPtr->prevSetupTZData;
    }

    ret = Tcl_ObjGetVar2(interp, dataPtr->literals[LIT_TZDATA],
	timezoneObj, TCL_LEAVE_ERR_MSG);
	    timezoneObj, TCL_LEAVE_ERR_MSG);

    /* cache using corresponding slot and as last used */
    if (out != NULL) {
	TclSetObjRef(*out, ret);
    }
    else
    if (dataPtr->lastSetupTimeZone != timezoneObj) {
    } else if (dataPtr->lastSetupTimeZone != timezoneObj) {
	SavePrevTimezoneObj(dataPtr);
	TclSetObjRef(dataPtr->lastSetupTimeZone, timezoneObj);
	TclUnsetObjRef(dataPtr->lastSetupTimeZoneUnnorm);
	TclSetObjRef(dataPtr->lastSetupTZData, ret);
    }
    return ret;
}
1265
1266
1267
1268
1269
1270
1271
1272

1273
1274
1275
1276
1277
1278
1279
1241
1242
1243
1244
1245
1246
1247

1248
1249
1250
1251
1252
1253
1254
1255







-
+







 *	Returns normalized timezone object.
 *
 *----------------------------------------------------------------------
 */

static Tcl_Obj *
ClockGetSystemTimeZone(
    void *clientData,	/* Opaque pointer to literal pool, etc. */
    void *clientData,		/* Opaque pointer to literal pool, etc. */
    Tcl_Interp *interp)		/* Tcl interpreter */
{
    ClockClientData *dataPtr = (ClockClientData *)clientData;

    /* if known (cached and same epoch) - return now */
    if (dataPtr->systemTimeZone != NULL
	    && dataPtr->lastTZEpoch == TzsetIfNecessary()) {
1304
1305
1306
1307
1308
1309
1310
1311

1312
1313
1314
1315
1316
1317
1318
1319
1320
1321


1322
1323
1324
1325
1326
1327



1328
1329
1330
1331
1332
1333



1334
1335
1336
1337
1338
1339
1340
1341
1280
1281
1282
1283
1284
1285
1286

1287
1288
1289
1290
1291
1292
1293
1294
1295


1296
1297

1298
1299



1300
1301
1302

1303
1304



1305
1306
1307

1308
1309
1310
1311
1312
1313
1314







-
+








-
-
+
+
-


-
-
-
+
+
+
-


-
-
-
+
+
+
-







 *	Returns normalized timezone object.
 *
 *----------------------------------------------------------------------
 */

Tcl_Obj *
ClockSetupTimeZone(
    void *clientData,	/* Opaque pointer to literal pool, etc. */
    void *clientData,		/* Opaque pointer to literal pool, etc. */
    Tcl_Interp *interp,		/* Tcl interpreter */
    Tcl_Obj *timezoneObj)
{
    ClockClientData *dataPtr = (ClockClientData *)clientData;
    int loaded;
    Tcl_Obj *callargs[2];

    /* if cached (if already setup this one) */
    if ( timezoneObj == dataPtr->literals[LIT_GMT]
      && dataPtr->gmtSetupTZData != NULL
    if (timezoneObj == dataPtr->literals[LIT_GMT]
	    && dataPtr->gmtSetupTZData != NULL) {
    ) {
	return timezoneObj;
    }
    if ( ( timezoneObj == dataPtr->lastSetupTimeZone
	|| timezoneObj == dataPtr->lastSetupTimeZoneUnnorm
      ) && dataPtr->lastSetupTimeZone != NULL
    if ((timezoneObj == dataPtr->lastSetupTimeZone
	    || timezoneObj == dataPtr->lastSetupTimeZoneUnnorm)
	    && dataPtr->lastSetupTimeZone != NULL) {
    ) {
	return dataPtr->lastSetupTimeZone;
    }
    if ( ( timezoneObj == dataPtr->prevSetupTimeZone
	|| timezoneObj == dataPtr->prevSetupTimeZoneUnnorm
      ) && dataPtr->prevSetupTimeZone != NULL
    if ((timezoneObj == dataPtr->prevSetupTimeZone
	    || timezoneObj == dataPtr->prevSetupTimeZoneUnnorm)
	    && dataPtr->prevSetupTimeZone != NULL) {
    ) {
	return dataPtr->prevSetupTimeZone;
    }

    /* differentiate normalized (last, GMT and system) zones, because used often and already set */
    callargs[1] = NormTimezoneObj(dataPtr, timezoneObj, &loaded);
    /* if loaded (setup already called for this TZ) */
    if (loaded) {
1374
1375
1376
1377
1378
1379
1380
1381
1382




1383
1384

1385
1386
1387
1388
1389
1390
1391




1392
1393

1394
1395
1396
1397
1398
1399
1400
1347
1348
1349
1350
1351
1352
1353


1354
1355
1356
1357
1358

1359
1360
1361
1362
1363
1364


1365
1366
1367
1368
1369

1370
1371
1372
1373
1374
1375
1376
1377







-
-
+
+
+
+

-
+





-
-
+
+
+
+

-
+







 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

Tcl_Obj *
ClockFormatNumericTimeZone(int z) {
    char buf[12+1], *p;
ClockFormatNumericTimeZone(
    int z)
{
    char buf[12 + 1], *p;

    if ( z < 0 ) {
    if (z < 0) {
	z = -z;
	*buf = '-';
    } else {
	*buf = '+';
    }
    TclItoAw(buf+1, z / 3600, '0', 2);   z %= 3600;
    p = TclItoAw(buf+3, z / 60, '0', 2); z %= 60;
    TclItoAw(buf + 1, z / 3600, '0', 2);
    z %= 3600;
    p = TclItoAw(buf + 3, z / 60, '0', 2);
    z %= 60;
    if (z != 0) {
	p = TclItoAw(buf+5, z, '0', 2);
	p = TclItoAw(buf + 5, z, '0', 2);
    }
    return Tcl_NewStringObj(buf, p - buf);
}

/*
 *----------------------------------------------------------------------
 *
1420
1421
1422
1423
1424
1425
1426
1427

1428
1429
1430
1431
1432
1433
1434
1397
1398
1399
1400
1401
1402
1403

1404
1405
1406
1407
1408
1409
1410
1411







-
+







 *	leaves an error message in the interpreter result.
 *
 *----------------------------------------------------------------------
 */

static int
ClockConvertlocaltoutcObjCmd(
    void *clientData,	/* Client data */
    void *clientData,		/* Client data */
    Tcl_Interp *interp,		/* Tcl interpreter */
    int objc,			/* Parameter count */
    Tcl_Obj *const *objv)	/* Parameter vector */
{
    ClockClientData *data = (ClockClientData *)clientData;
    Tcl_Obj *secondsObj;
    Tcl_Obj *dict;
1452
1453
1454
1455
1456
1457
1458
1459

1460
1461
1462


1463
1464
1465
1466
1467
1468
1469
1429
1430
1431
1432
1433
1434
1435

1436



1437
1438
1439
1440
1441
1442
1443
1444
1445







-
+
-
-
-
+
+







	return TCL_ERROR;
    }
    if (secondsObj == NULL) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("key \"localseconds\" not "
		"found in dictionary", -1));
	return TCL_ERROR;
    }
    if ((TclGetWideIntFromObj(interp, secondsObj,
    if ((TclGetWideIntFromObj(interp, secondsObj, &fields.localSeconds) != TCL_OK)
	    &fields.localSeconds) != TCL_OK)
	|| (TclGetIntFromObj(interp, objv[3], &changeover) != TCL_OK)
	|| ConvertLocalToUTC(clientData, interp, &fields, objv[2], changeover)) {
	    || (TclGetIntFromObj(interp, objv[3], &changeover) != TCL_OK)
	    || ConvertLocalToUTC(clientData, interp, &fields, objv[2], changeover)) {
	return TCL_ERROR;
    }

    /*
     * Copy-on-write; set the 'seconds' field in the dictionary and place the
     * modified dictionary in the interpreter result.
     */
1511
1512
1513
1514
1515
1516
1517
1518

1519
1520
1521
1522
1523
1524
1525
1487
1488
1489
1490
1491
1492
1493

1494
1495
1496
1497
1498
1499
1500
1501







-
+







 *		julianDay - Julian Day Number in the local time zone
 *
 *----------------------------------------------------------------------
 */

int
ClockGetdatefieldsObjCmd(
    void *clientData,	/* Opaque pointer to literal pool, etc. */
    void *clientData,		/* Opaque pointer to literal pool, etc. */
    Tcl_Interp *interp,		/* Tcl interpreter */
    int objc,			/* Parameter count */
    Tcl_Obj *const *objv)	/* Parameter vector */
{
    TclDateFields fields;
    Tcl_Obj *dict;
    ClockClientData *data = (ClockClientData *)clientData;
1550
1551
1552
1553
1554
1555
1556
1557

1558
1559
1560
1561
1562
1563
1564
1526
1527
1528
1529
1530
1531
1532

1533
1534
1535
1536
1537
1538
1539
1540







-
+







	Tcl_SetObjResult(interp, lit[LIT_INTEGER_VALUE_TOO_LARGE]);
	return TCL_ERROR;
    }

    /* Extract fields */

    if (ClockGetDateFields(clientData, interp, &fields, objv[2],
	  changeover) != TCL_OK) {
	    changeover) != TCL_OK) {
	return TCL_ERROR;
    }

    /* Make dict of fields */

    dict = Tcl_NewDictObj();
    Tcl_DictObjPut(NULL, dict, lit[LIT_LOCALSECONDS],
1608
1609
1610
1611
1612
1613
1614
1615

1616
1617
1618
1619
1620
1621
1622
1584
1585
1586
1587
1588
1589
1590

1591
1592
1593
1594
1595
1596
1597
1598







-
+







 *	Returns a standard Tcl result.
 *
 *----------------------------------------------------------------------
 */

int
ClockGetDateFields(
    void *clientData,	/* Client data of the interpreter */
    void *clientData,		/* Client data of the interpreter */
    Tcl_Interp *interp,		/* Tcl interpreter */
    TclDateFields *fields,	/* Pointer to result fields, where
				 * fields->seconds contains date to extract */
    Tcl_Obj *timezoneObj,	/* Time zone object or NULL for gmt */
    int changeover)		/* Julian Day Number */
{
    /*
1705
1706
1707
1708
1709
1710
1711
1712

1713
1714
1715
1716
1717
1718
1719
1681
1682
1683
1684
1685
1686
1687

1688
1689
1690
1691
1692
1693
1694
1695







-
+







	return TCL_ERROR;
    }
    return TclGetIntFromObj(interp, value, storePtr);
}

static int
ClockGetjuliandayfromerayearmonthdayObjCmd(
    void *clientData,	/* Opaque pointer to literal pool, etc. */
    void *clientData,		/* Opaque pointer to literal pool, etc. */
    Tcl_Interp *interp,		/* Tcl interpreter */
    int objc,			/* Parameter count */
    Tcl_Obj *const *objv)	/* Parameter vector */
{
    TclDateFields fields;
    Tcl_Obj *dict;
    ClockClientData *data = (ClockClientData *)clientData;
1791
1792
1793
1794
1795
1796
1797
1798

1799
1800
1801
1802
1803
1804
1805
1767
1768
1769
1770
1771
1772
1773

1774
1775
1776
1777
1778
1779
1780
1781







-
+







 *	result being an error message.
 *
 *----------------------------------------------------------------------
 */

static int
ClockGetjuliandayfromerayearweekdayObjCmd(
    void *clientData,	/* Opaque pointer to literal pool, etc. */
    void *clientData,		/* Opaque pointer to literal pool, etc. */
    Tcl_Interp *interp,		/* Tcl interpreter */
    int objc,			/* Parameter count */
    Tcl_Obj *const *objv)	/* Parameter vector */
{
    TclDateFields fields;
    Tcl_Obj *dict;
    ClockClientData *data = (ClockClientData *)clientData;
1874
1875
1876
1877
1878
1879
1880
1881

1882
1883
1884
1885
1886
1887
1888
1889

1890
1891
1892
1893
1894
1895
1896
1850
1851
1852
1853
1854
1855
1856

1857
1858
1859
1860
1861
1862
1863
1864

1865
1866
1867
1868
1869
1870
1871
1872







-
+







-
+







 *	in the interpreter result on failure.
 *
 *----------------------------------------------------------------------
 */

static int
ConvertLocalToUTC(
    void *clientData,	/* Client data of the interpreter */
    void *clientData,		/* Client data of the interpreter */
    Tcl_Interp *interp,		/* Tcl interpreter */
    TclDateFields *fields,	/* Fields of the time */
    Tcl_Obj *timezoneObj,	/* Time zone */
    int changeover)		/* Julian Day of the Gregorian transition */
{
    ClockClientData *dataPtr = (ClockClientData *)clientData;
    Tcl_Obj *tzdata;		/* Time zone data */
    Tcl_Size rowc;			/* Number of rows in tzdata */
    Tcl_Size rowc;		/* Number of rows in tzdata */
    Tcl_Obj **rowv;		/* Pointers to the rows */
    Tcl_WideInt seconds;
    ClockLastTZOffs * ltzoc = NULL;

    /* fast phase-out for shared GMT-object (don't need to convert UTC 2 UTC) */
    if (timezoneObj == dataPtr->literals[LIT_GMT]) {
	fields->seconds = fields->localSeconds;
1905
1906
1907
1908
1909
1910
1911
1912
1913


1914
1915
1916
1917
1918
1919
1920
1921
1881
1882
1883
1884
1885
1886
1887


1888
1889

1890
1891
1892
1893
1894
1895
1896







-
-
+
+
-







    for (rowc = 0; rowc < 2; rowc++) {
	ltzoc = &dataPtr->lastTZOffsCache[rowc];
	if (timezoneObj != ltzoc->timezoneObj || changeover != ltzoc->changeover) {
	    ltzoc = NULL;
	    continue;
	}
	seconds = fields->localSeconds - ltzoc->tzOffset;
	if ( seconds >= ltzoc->rangesVal[0]
	  && seconds <  ltzoc->rangesVal[1]
	if (seconds >= ltzoc->rangesVal[0]
		&& seconds < ltzoc->rangesVal[1]) {
	) {
	    /* the same time zone and offset (UTC time inside the last minute) */
	    fields->tzOffset = ltzoc->tzOffset;
	    fields->seconds = seconds;
	    return TCL_OK;
	}
	/* in the DST-hole (because of the check above) - correct localSeconds */
	if (fields->localSeconds == ltzoc->localSeconds) {
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951

1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962

1963
1964
1965
1966
1967
1968
1969
1916
1917
1918
1919
1920
1921
1922

1923
1924

1925
1926
1927
1928

1929
1930
1931
1932
1933
1934

1935
1936
1937
1938
1939
1940
1941
1942







-


-
+



-






-
+








    /*
     * Special case: If the time zone is :localtime, the tzdata will be empty.
     * Use 'mktime' to convert the time to local
     */

    if (rowc == 0) {

	if (ConvertLocalToUTCUsingC(interp, fields, changeover) != TCL_OK) {
	    return TCL_ERROR;
	};
	}

	/* we cannot cache (ranges unknown yet) - todo: check later the DST-hole here */
	return TCL_OK;

    } else {
	Tcl_WideInt rangesVal[2];

	if (ConvertLocalToUTCUsingTable(interp, fields, rowc, rowv,
		rangesVal) != TCL_OK) {
	    return TCL_ERROR;
	};
	}

	seconds = fields->seconds;

	/* Cache the last conversion */
	if (ltzoc != NULL) { /* slot was found above */
	    /* timezoneObj and changeover are the same */
	    TclSetObjRef(ltzoc->tzName, fields->tzName); /* may be NULL */
1981
1982
1983
1984
1985
1986
1987
1988

1989
1990

1991
1992
1993
1994
1995

1996
1997
1998
1999
2000
2001
2002
1954
1955
1956
1957
1958
1959
1960

1961
1962

1963
1964
1965
1966
1967

1968
1969
1970
1971
1972
1973
1974
1975







-
+

-
+




-
+







	ltzoc->rangesVal[0] = rangesVal[0];
	ltzoc->rangesVal[1] = rangesVal[1];
	ltzoc->tzOffset = fields->tzOffset;
    }


    /* check DST-hole: if retrieved seconds is out of range */
    if ( ltzoc->rangesVal[0] > seconds || seconds >= ltzoc->rangesVal[1] ) {
    if (ltzoc->rangesVal[0] > seconds || seconds >= ltzoc->rangesVal[1]) {
    dstHole:
	#if 0
#if 0
	printf("given local-time is outside the time-zone (in DST-hole): "
		"%d - offs %d => %d <= %d < %d\n",
		(int)fields->localSeconds, fields->tzOffset,
		(int)ltzoc->rangesVal[0], (int)seconds, (int)ltzoc->rangesVal[1]);
	#endif
#endif
	/* because we don't know real TZ (we're outsize), just invalidate local
	 * time (which could be verified in ClockValidDate later) */
	fields->localSeconds = TCL_INV_SECONDS; /* not valid seconds */
    }
    return TCL_OK;
}

2046
2047
2048
2049
2050
2051
2052
2053

2054
2055
2056
2057
2058
2059
2060
2061
2062
2063

2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2019
2020
2021
2022
2023
2024
2025

2026
2027
2028
2029
2030
2031
2032
2033
2034
2035

2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046

2047
2048
2049
2050
2051
2052
2053







-
+









-
+










-







     * Saving Time transition.
     */

    fields->tzOffset = 0;
    fields->seconds = fields->localSeconds;
    while (1) {
	row = LookupLastTransition(interp, fields->seconds, rowc, rowv,
		    rangesVal);
		rangesVal);
	if ((row == NULL)
		|| TclListObjGetElements(interp, row, &cellc,
		    &cellv) != TCL_OK
		|| TclGetIntFromObj(interp, cellv[1],
		    &fields->tzOffset) != TCL_OK) {
	    return TCL_ERROR;
	}
	for (i = 0; i < nHave; ++i) {
	    if (have[i].tzOffset == fields->tzOffset) {
		goto found;
		break;
	    }
	}
	if (nHave == 8) {
	    Tcl_Panic("loop in ConvertLocalToUTCUsingTable");
	}
	have[nHave].tzName = cellv[3];
	have[nHave++].tzOffset = fields->tzOffset;
	fields->seconds = fields->localSeconds - fields->tzOffset;
    }

  found:
    fields->tzOffset = have[i].tzOffset;
    fields->seconds = fields->localSeconds - fields->tzOffset;
    TclSetObjRef(fields->tzName, have[i].tzName);

    return TCL_OK;
}

2108
2109
2110
2111
2112
2113
2114
2115

2116
2117
2118
2119
2120
2121
2122
2080
2081
2082
2083
2084
2085
2086

2087
2088
2089
2090
2091
2092
2093
2094







-
+







    int secondOfDay;

    /*
     * Convert the given time to a date.
     */

    ClockExtractJDAndSODFromSeconds(fields->julianDay, secondOfDay,
	fields->localSeconds);
	    fields->localSeconds);

    GetGregorianEraYearDay(fields, changeover);
    GetMonthDay(fields);

    /*
     * Convert the date/time to a 'struct tm'.
     */
2170
2171
2172
2173
2174
2175
2176
2177

2178
2179
2180
2181
2182
2183
2184
2185

2186
2187
2188
2189
2190
2191
2192
2193
2194

2195
2196
2197


2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217


2218
2219
2220
2221
2222
2223
2224
2225
2142
2143
2144
2145
2146
2147
2148

2149
2150
2151
2152
2153
2154
2155
2156

2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168


2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188


2189
2190

2191
2192
2193
2194
2195
2196
2197







-
+







-
+









+

-
-
+
+


















-
-
+
+
-







 *	Populates the 'tzName' and 'tzOffset' fields.
 *
 *----------------------------------------------------------------------
 */

int
ConvertUTCToLocal(
    void *clientData,	/* Client data of the interpreter */
    void *clientData,		/* Client data of the interpreter */
    Tcl_Interp *interp,		/* Tcl interpreter */
    TclDateFields *fields,	/* Fields of the time */
    Tcl_Obj *timezoneObj,	/* Time zone */
    int changeover)		/* Julian Day of the Gregorian transition */
{
    ClockClientData *dataPtr = (ClockClientData *)clientData;
    Tcl_Obj *tzdata;		/* Time zone data */
    Tcl_Size rowc;			/* Number of rows in tzdata */
    Tcl_Size rowc;		/* Number of rows in tzdata */
    Tcl_Obj **rowv;		/* Pointers to the rows */
    ClockLastTZOffs * ltzoc = NULL;

    /* fast phase-out for shared GMT-object (don't need to convert UTC 2 UTC) */
    if (timezoneObj == dataPtr->literals[LIT_GMT]) {
	fields->localSeconds = fields->seconds;
	fields->tzOffset = 0;
	if (dataPtr->gmtTZName == NULL) {
	    Tcl_Obj *tzName;

	    tzdata = ClockGetTZData(clientData, interp, timezoneObj);
	    if ( TclListObjGetElements(interp, tzdata, &rowc, &rowv) != TCL_OK
	      || Tcl_ListObjIndex(interp, rowv[0], 3, &tzName) != TCL_OK) {
	    if (TclListObjGetElements(interp, tzdata, &rowc, &rowv) != TCL_OK
		    || Tcl_ListObjIndex(interp, rowv[0], 3, &tzName) != TCL_OK) {
		return TCL_ERROR;
	    }
	    TclSetObjRef(dataPtr->gmtTZName, tzName);
	}
	TclSetObjRef(fields->tzName, dataPtr->gmtTZName);
	return TCL_OK;
    }

    /*
     * Check cacheable conversion could be used
     * (last-period UTC2Local cache within the same TZ and seconds)
     */
    for (rowc = 0; rowc < 2; rowc++) {
	ltzoc = &dataPtr->lastTZOffsCache[rowc];
	if (timezoneObj != ltzoc->timezoneObj || changeover != ltzoc->changeover) {
	    ltzoc = NULL;
	    continue;
	}
	if ( fields->seconds >= ltzoc->rangesVal[0]
	  && fields->seconds <  ltzoc->rangesVal[1]
	if (fields->seconds >= ltzoc->rangesVal[0]
		&& fields->seconds < ltzoc->rangesVal[1]) {
	) {
	    /* the same time zone and offset (UTC time inside the last minute) */
	    fields->tzOffset = ltzoc->tzOffset;
	    fields->localSeconds = fields->seconds + fields->tzOffset;
	    TclSetObjRef(fields->tzName, ltzoc->tzName);
	    return TCL_OK;
	}
    }
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2211
2212
2213
2214
2215
2216
2217

2218
2219
2220
2221
2222
2223
2224







-








    /*
     * Special case: If the time zone is :localtime, the tzdata will be empty.
     * Use 'localtime' to convert the time to local
     */

    if (rowc == 0) {

	if (ConvertUTCToLocalUsingC(interp, fields, changeover) != TCL_OK) {
	    return TCL_ERROR;
	}

	/* signal we need to revalidate TZ epoch next time fields gets used. */
	fields->flags |= CLF_CTZ;

2304
2305
2306
2307
2308
2309
2310
2311

2312
2313
2314
2315
2316
2317

2318
2319
2320
2321
2322
2323
2324
2325
2326
2327



2328
2329
2330
2331
2332
2333
2334
2275
2276
2277
2278
2279
2280
2281

2282
2283
2284
2285
2286
2287

2288
2289
2290
2291
2292
2293
2294
2295



2296
2297
2298
2299
2300
2301
2302
2303
2304
2305







-
+





-
+







-
-
-
+
+
+







 *----------------------------------------------------------------------
 */

static int
ConvertUTCToLocalUsingTable(
    Tcl_Interp *interp,		/* Tcl interpreter */
    TclDateFields *fields,	/* Fields of the date */
    Tcl_Size rowc,			/* Number of rows in the conversion table
    Tcl_Size rowc,		/* Number of rows in the conversion table
				 * (>= 1) */
    Tcl_Obj *const rowv[],	/* Rows of the conversion table */
    Tcl_WideInt *rangesVal)	/* Return bounds for time period */
{
    Tcl_Obj *row;		/* Row containing the current information */
    Tcl_Size cellc;			/* Count of cells in the row (must be 4) */
    Tcl_Size cellc;		/* Count of cells in the row (must be 4) */
    Tcl_Obj **cellv;		/* Pointers to the cells */

    /*
     * Look up the nearest transition time.
     */

    row = LookupLastTransition(interp, fields->seconds, rowc, rowv, rangesVal);
    if (row == NULL ||
	    TclListObjGetElements(interp, row, &cellc, &cellv) != TCL_OK ||
	    TclGetIntFromObj(interp, cellv[1], &fields->tzOffset) != TCL_OK) {
    if (row == NULL
	    || TclListObjGetElements(interp, row, &cellc, &cellv) != TCL_OK
	    || TclGetIntFromObj(interp, cellv[1], &fields->tzOffset) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Convert the time.
     */

2414
2415
2416
2417
2418
2419
2420
2421
2422




2423
2424

2425
2426
2427
2428
2429
2430
2431
2385
2386
2387
2388
2389
2390
2391


2392
2393
2394
2395
2396

2397
2398
2399
2400
2401
2402
2403
2404







-
-
+
+
+
+

-
+







    fields->tzOffset = diff;
    if (diff < 0) {
	*buffer = '-';
	diff = -diff;
    } else {
	*buffer = '+';
    }
    TclItoAw(buffer+1, diff / 3600, '0', 2);   diff %= 3600;
    p = TclItoAw(buffer+3, diff / 60, '0', 2); diff %= 60;
    TclItoAw(buffer + 1, diff / 3600, '0', 2);
    diff %= 3600;
    p = TclItoAw(buffer + 3, diff / 60, '0', 2);
    diff %= 60;
    if (diff != 0) {
	p = TclItoAw(buffer+5, diff, '0', 2);
	p = TclItoAw(buffer + 5, diff, '0', 2);
    }
    TclSetObjRef(fields->tzName, Tcl_NewStringObj(buffer, p - buffer));
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
2441
2442
2443
2444
2445
2446
2447
2448

2449
2450
2451
2452

2453
2454
2455
2456
2457
2458
2459
2414
2415
2416
2417
2418
2419
2420

2421
2422
2423
2424

2425
2426
2427
2428
2429
2430
2431
2432







-
+



-
+







 *----------------------------------------------------------------------
 */

Tcl_Obj *
LookupLastTransition(
    Tcl_Interp *interp,		/* Interpreter for error messages */
    Tcl_WideInt tick,		/* Time from the epoch */
    Tcl_Size rowc,			/* Number of rows of tzdata */
    Tcl_Size rowc,		/* Number of rows of tzdata */
    Tcl_Obj *const *rowv,	/* Rows in tzdata */
    Tcl_WideInt *rangesVal)	/* Return bounds for time period */
{
	Tcl_Size l, u;
    Tcl_Size l, u;
    Tcl_Obj *compObj;
    Tcl_WideInt compVal, fromVal = LLONG_MIN, toVal = LLONG_MAX;

    /*
     * Examine the first row to make sure we're in bounds.
     */

2476
2477
2478
2479
2480
2481
2482
2483

2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495

2496
2497
2498
2499
2500
2501
2502
2449
2450
2451
2452
2453
2454
2455

2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467

2468
2469
2470
2471
2472
2473
2474
2475







-
+











-
+







    }

    /*
     * Binary-search to find the transition.
     */

    l = 0;
    u = rowc-1;
    u = rowc - 1;
    while (l < u) {
	Tcl_Size m = (l + u + 1) / 2;

	if (Tcl_ListObjIndex(interp, rowv[m], 0, &compObj) != TCL_OK ||
		TclGetWideIntFromObj(interp, compObj, &compVal) != TCL_OK) {
	    return NULL;
	}
	if (tick >= compVal) {
	    l = m;
	    fromVal = compVal;
	} else {
	    u = m-1;
	    u = m - 1;
	    toVal = compVal;
	}
    }

    if (rangesVal) {
	rangesVal[0] = fromVal;
	rangesVal[1] = toVal;
2718
2719
2720
2721
2722
2723
2724
2725

2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737

2738
2739
2740
2741
2742
2743
2744
2691
2692
2693
2694
2695
2696
2697

2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709

2710
2711
2712
2713
2714
2715
2716
2717







-
+











-
+







    /*
     * Estimate month by calculating `dayOfYear / (365/12)`
     */
    month = (day*12) / dipm[12];
    /* then do forwards backwards correction */
    while (1) {
	if (day > dipm[month]) {
	    if (month >= 11 || day <= dipm[month+1]) {
	    if (month >= 11 || day <= dipm[month + 1]) {
		break;
	    }
	    month++;
	} else {
	    if (month == 0) {
		break;
	    }
	    month--;
	}
    }
    day -= dipm[month];
    fields->month = month+1;
    fields->month = month + 1;
    fields->dayOfMonth = day;
}

/*
 *----------------------------------------------------------------------
 *
 * GetJulianDayFromEraYearWeekDay --
2841
2842
2843
2844
2845
2846
2847
2848

2849
2850
2851
2852
2853
2854
2855
2814
2815
2816
2817
2818
2819
2820

2821
2822
2823
2824
2825
2826
2827
2828







-
+







    /*
     * Adjust the year after reducing the month.
     */

    fields->gregorian = 1;
    if (year < 1) {
	fields->isBce = 1;
	fields->year = 1-year;
	fields->year = 1 - year;
    } else {
	fields->isBce = 0;
	fields->year = year;
    }

    /*
     * Try an initial conversion in the Gregorian calendar.
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947






2948
2949
2950
2951

2952
2953
2954
2955
2956
2957




2958
2959
2960
2961
2962
2963
2964
2908
2909
2910
2911
2912
2913
2914






2915
2916
2917
2918
2919
2920
2921
2922
2923

2924
2925
2926




2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937







-
-
-
-
-
-
+
+
+
+
+
+



-
+


-
-
-
-
+
+
+
+







    }

    ym1 = year - 1;

    /* Try the Gregorian calendar first. */
    fields->gregorian = 1;
    fields->julianDay =
	1721425
	+ fields->dayOfYear
	+ ( 365 * ym1 )
	+ ( ym1 / 4 )
	- ( ym1 / 100 )
	+ ( ym1 / 400 );
	    1721425
	    + fields->dayOfYear
	    + (365 * ym1)
	    + (ym1 / 4)
	    - (ym1 / 100)
	    + (ym1 / 400);

    /* If the date is before the Gregorian change, use the Julian calendar. */

    if ( fields->julianDay < changeover ) {
    if (fields->julianDay < changeover) {
	fields->gregorian = 0;
	fields->julianDay =
	    1721423
	    + fields->dayOfYear
	    + ( 365 * ym1 )
	    + ( ym1 / 4 );
		1721423
		+ fields->dayOfYear
		+ (365 * ym1)
		+ (ym1 / 4);
    }
}
/*
 *----------------------------------------------------------------------
 *
 * IsGregorianLeapYear --
 *
2976
2977
2978
2979
2980
2981
2982
2983

2984
2985
2986
2987

2988
2989

2990
2991
2992
2993
2994
2995
2996
2949
2950
2951
2952
2953
2954
2955

2956
2957
2958
2959

2960
2961

2962
2963
2964
2965
2966
2967
2968
2969







-
+



-
+

-
+







    TclDateFields *fields)	/* Date to test */
{
    Tcl_WideInt year = fields->year;

    if (fields->isBce) {
	year = 1 - year;
    }
    if (year%4 != 0) {
    if (year % 4 != 0) {
	return 0;
    } else if (!(fields->gregorian)) {
	return 1;
    } else if (year%400 == 0) {
    } else if (year % 400 == 0) {
	return 1;
    } else if (year%100 == 0) {
    } else if (year % 100 == 0) {
	return 0;
    } else {
	return 1;
    }
}

/*
3103
3104
3105
3106
3107
3108
3109
3110

3111
3112
3113
3114
3115
3116
3117
3076
3077
3078
3079
3080
3081
3082

3083
3084
3085
3086
3087
3088
3089
3090







-
+







    const time_t *timePtr)	/* Pointer to the number of seconds since the
				 * local system's epoch */
{
    /*
     * Get a thread-local buffer to hold the returned time.
     */

    struct tm *tmPtr = (struct tm *)Tcl_GetThreadData(&tmKey, sizeof(struct tm));
    struct tm *tmPtr = (struct tm *) Tcl_GetThreadData(&tmKey, sizeof(struct tm));
#ifdef HAVE_LOCALTIME_R
    tmPtr = localtime_r(timePtr, tmPtr);
#else
    struct tm *sysTmPtr;

    Tcl_MutexLock(&clockMutex);
    sysTmPtr = localtime(timePtr);
3303
3304
3305
3306
3307
3308
3309
3310
3311


3312
3313


3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328

3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344

3345
3346
3347
3348
3349
3350
3351

3352
3353
3354
3355
3356
3357


3358
3359
3360
3361
3362


3363
3364
3365
3366
3367
3368
3369
3370
3371

3372
3373
3374

3375
3376
3377
3378
3379

3380
3381
3382

3383
3384
3385

3386
3387
3388

3389
3390
3391

3392

3393
3394
3395
3396
3397
3398
3399
3276
3277
3278
3279
3280
3281
3282


3283
3284


3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300

3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324

3325
3326
3327
3328
3329


3330
3331
3332
3333
3334


3335
3336

3337
3338
3339
3340
3341
3342
3343

3344
3345
3346

3347
3348
3349
3350
3351

3352
3353
3354

3355
3356
3357

3358
3359
3360

3361
3362
3363
3364
3365

3366
3367
3368
3369
3370
3371
3372
3373







-
-
+
+
-
-
+
+














-
+
















+






-
+




-
-
+
+



-
-
+
+
-







-
+


-
+




-
+


-
+


-
+


-
+



+
-
+







static int
ClockParseFmtScnArgs(
    ClockFmtScnCmdArgs *opts,	/* Result vector: format, locale, timezone... */
    TclDateFields      *date,	/* Extracted date-time corresponding base
				 * (by scan or add) resp. clockval (by format) */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[],	/* Parameter vector */
    int		flags,		/* Flags, differentiates between format, scan, add */
    const char *syntax		/* Syntax of the current command */
    int flags,			/* Flags, differentiates between format, scan, add */
    const char *syntax)		/* Syntax of the current command */
) {
    Tcl_Interp	    *interp =  opts->interp;
{
    Tcl_Interp *interp = opts->interp;
    ClockClientData *dataPtr = (ClockClientData *)opts->clientData;
    int gmtFlag = 0;
    static const char *const options[] = {
	"-base", "-format", "-gmt", "-locale", "-timezone", "-validate", NULL
    };
    enum optionInd {
	CLC_ARGS_BASE, CLC_ARGS_FORMAT, CLC_ARGS_GMT, CLC_ARGS_LOCALE,
	CLC_ARGS_TIMEZONE, CLC_ARGS_VALIDATE
    };
    int optionIndex;		/* Index of an option. */
    int saw = 0;		/* Flag == 1 if option was seen already. */
    int i, baseIdx;
    Tcl_WideInt baseVal;	/* Base time, expressed in seconds from the Epoch */

    if ( flags & (CLC_SCN_ARGS) ) {
    if (flags & CLC_SCN_ARGS) {
    	/* default flags (from configure) */
    	opts->flags |= dataPtr->defFlags & (CLF_VALIDATE);
    } else {
    	/* clock value (as current base) */
	opts->baseObj = objv[(baseIdx = 1)];
	saw |= (1 << CLC_ARGS_BASE);
    }

    /*
     * Extract values for the keywords.
     */

    for (i = 2; i < objc; i+=2) {
	/* bypass integers (offsets) by "clock add" */
	if (flags & CLC_ADD_ARGS) {
	    Tcl_WideInt num;

	    if (TclGetWideIntFromObj(NULL, objv[i], &num) == TCL_OK) {
		continue;
	    }
	}
	/* get option */
	if (Tcl_GetIndexFromObj(interp, objv[i], options,
	    "option", 0, &optionIndex) != TCL_OK) {
		"option", 0, &optionIndex) != TCL_OK) {
	    goto badOptionMsg;
	}
	/* if already specified */
	if (saw & (1 << optionIndex)) {
	    if ( !(flags & CLC_SCN_ARGS)
	       && optionIndex == CLC_ARGS_BASE) {
	    if (!(flags & CLC_SCN_ARGS)
		    && optionIndex == CLC_ARGS_BASE) {
		goto badOptionMsg;
	    }
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"bad option \"%s\": doubly present",
		TclGetString(objv[i]))
		    "bad option \"%s\": doubly present",
		    TclGetString(objv[i])));
	    );
	    goto badOption;
	}
	switch (optionIndex) {
	case CLC_ARGS_FORMAT:
	    if (flags & CLC_ADD_ARGS) {
		goto badOptionMsg;
	    }
	    opts->formatObj = objv[i+1];
	    opts->formatObj = objv[i + 1];
	    break;
	case CLC_ARGS_GMT:
	    if (Tcl_GetBooleanFromObj(interp, objv[i+1], &gmtFlag) != TCL_OK){
	    if (Tcl_GetBooleanFromObj(interp, objv[i + 1], &gmtFlag) != TCL_OK){
		return TCL_ERROR;
	    }
	    break;
	case CLC_ARGS_LOCALE:
	    opts->localeObj = objv[i+1];
	    opts->localeObj = objv[i + 1];
	    break;
	case CLC_ARGS_TIMEZONE:
	    opts->timezoneObj = objv[i+1];
	    opts->timezoneObj = objv[i + 1];
	    break;
	case CLC_ARGS_BASE:
	    opts->baseObj = objv[(baseIdx = i+1)];
	    opts->baseObj = objv[(baseIdx = i + 1)];
	    break;
	case CLC_ARGS_VALIDATE:
	    if ( !(flags & CLC_SCN_ARGS) ) {
	    if (!(flags & CLC_SCN_ARGS)) {
		goto badOptionMsg;
	    } else {
		int val;

		if (Tcl_GetBooleanFromObj(interp, objv[i+1], &val) != TCL_OK) {
		if (Tcl_GetBooleanFromObj(interp, objv[i + 1], &val) != TCL_OK) {
		    return TCL_ERROR;
		}
		if (val) {
		    opts->flags |= CLF_VALIDATE;
		} else {
		    opts->flags &= ~CLF_VALIDATE;
		}
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423



3424

3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441

3442
3443
3444
3445


3446
3447
3448
3449
3450
3451
3452

3453
3454

3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476

3477
3478

3479
3480
3481
3482
3483
3484

3485
3486

3487
3488
3489
3490


3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503




3504
3505
3506
3507
3508
3509
3510


3511
3512
3513
3514
3515
3516
3517
3518
3519
3520

3521
3522
3523
3524


3525
3526
3527

3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3385
3386
3387
3388
3389
3390
3391






3392
3393
3394

3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414



3415
3416


3417
3418
3419
3420
3421
3422
3423

3424

3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444

3445


3446
3447
3448
3449
3450

3451
3452
3453

3454




3455
3456

3457
3458
3459
3460
3461
3462
3463
3464




3465
3466
3467
3468

3469
3470
3471
3472
3473

3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484

3485

3486


3487
3488

3489

3490

3491
3492

3493
3494
3495
3496
3497
3498
3499







-
-
-
-
-
-
+
+
+
-
+

















+

-
-
-
+
+
-
-





+

-
+
-




















-
+
-
-
+




-

+

-
+
-
-
-
-
+
+
-








-
-
-
-
+
+
+
+
-





-
+
+









-
+
-

-
-
+
+
-

-
+
-


-







	    && (saw & (1 << CLC_ARGS_TIMEZONE))) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot use -gmt and -timezone in same call", -1));
	Tcl_SetErrorCode(interp, "CLOCK", "gmtWithTimezone", (char *)NULL);
	return TCL_ERROR;
    }
    if (gmtFlag) {
	opts->timezoneObj = dataPtr->literals[LIT_GMT];
    }
    else
    /* If time zone not specified use system time zone */
    if ( opts->timezoneObj == NULL
      || TclGetString(opts->timezoneObj) == NULL
      || opts->timezoneObj->length == 0
    } else if (opts->timezoneObj == NULL
	    || TclGetString(opts->timezoneObj) == NULL
	    || opts->timezoneObj->length == 0) {
    ) {
	/* If time zone not specified use system time zone */
	opts->timezoneObj = ClockGetSystemTimeZone(opts->clientData, interp);
	if (opts->timezoneObj == NULL) {
	    return TCL_ERROR;
	}
    }

    /* Setup timezone (normalize object if needed and load TZ on demand) */

    opts->timezoneObj = ClockSetupTimeZone(opts->clientData, interp, opts->timezoneObj);
    if (opts->timezoneObj == NULL) {
	return TCL_ERROR;
    }

    /* Base (by scan or add) or clock value (by format) */

    if (opts->baseObj != NULL) {
	Tcl_Obj *baseObj = opts->baseObj;

	/* bypass integer recognition if looks like option "-now" */
	if (
	    (baseObj->bytes && baseObj->length == 4 && *(baseObj->bytes+1) == 'n') ||
	    TclGetWideIntFromObj(NULL, baseObj, &baseVal) != TCL_OK
	if ((baseObj->bytes && baseObj->length == 4 && *(baseObj->bytes + 1) == 'n')
		|| TclGetWideIntFromObj(NULL, baseObj, &baseVal) != TCL_OK) {
	) {

	    /* we accept "-now" as current date-time */
	    static const char *const nowOpts[] = {
		"-now", NULL
	    };
	    int idx;

	    if (Tcl_GetIndexFromObj(interp, baseObj, nowOpts, "seconds",
		    TCL_EXACT, &idx) == TCL_OK
		    TCL_EXACT, &idx) == TCL_OK) {
	    ) {
		goto baseNow;
	    }

	    if (TclHasInternalRep(baseObj, &tclBignumType)) {
		goto baseOverflow;
	    }

	    Tcl_AppendResult(interp, " or integer", NULL);
	    i = baseIdx;
	    goto badOption;
	}
	/*
	 * Seconds could be an unsigned number that overflowed. Make sure
	 * that it isn't. Additionally it may be too complex to calculate
	 * julianday etc (forwards/backwards) by too large/small values, thus
	 * just let accept a bit shorter values to avoid overflow.
	 * Note the year is currently an integer, thus avoid to overflow it also.
	 */

	if (TclHasInternalRep(baseObj, &tclBignumType)
	  || baseVal < TCL_MIN_SECONDS || baseVal > TCL_MAX_SECONDS
		|| baseVal < TCL_MIN_SECONDS || baseVal > TCL_MAX_SECONDS) {
	) {
baseOverflow:
	baseOverflow:
	    Tcl_SetObjResult(interp, dataPtr->literals[LIT_INTEGER_VALUE_TOO_LARGE]);
	    i = baseIdx;
	    goto badOption;
	}

    } else {
	Tcl_Time now;

baseNow:
    baseNow:
	{
	    Tcl_Time now;
	    Tcl_GetTime(&now);
	    baseVal = (Tcl_WideInt) now.sec;
	Tcl_GetTime(&now);
	baseVal = (Tcl_WideInt) now.sec;
	}
    }

    /*
     * Extract year, month and day from the base time for the parser to use as
     * defaults
     */

    /* check base fields already cached (by TZ, last-second cache) */
    if ( dataPtr->lastBase.timezoneObj == opts->timezoneObj
      && dataPtr->lastBase.date.seconds == baseVal
      && (!(dataPtr->lastBase.date.flags & CLF_CTZ)
	     || dataPtr->lastTZEpoch == TzsetIfNecessary())
    if (dataPtr->lastBase.timezoneObj == opts->timezoneObj
	    && dataPtr->lastBase.date.seconds == baseVal
	    && (!(dataPtr->lastBase.date.flags & CLF_CTZ)
	    || dataPtr->lastTZEpoch == TzsetIfNecessary())) {
    ) {
	memcpy(date, &dataPtr->lastBase.date, ClockCacheableDateFieldsSize);
    } else {
	/* extact fields from base */
	date->seconds = baseVal;
	if (ClockGetDateFields(opts->clientData, interp, date, opts->timezoneObj,
	      GREGORIAN_CHANGE_DATE) != TCL_OK) { /* TODO - GREGORIAN_CHANGE_DATE should be locale-dependent */
	      GREGORIAN_CHANGE_DATE) != TCL_OK) {
	    /* TODO - GREGORIAN_CHANGE_DATE should be locale-dependent */
	    return TCL_ERROR;
	}
	/* cache last base */
	memcpy(&dataPtr->lastBase.date, date, ClockCacheableDateFieldsSize);
	TclSetObjRef(dataPtr->lastBase.timezoneObj, opts->timezoneObj);
    }

    return TCL_OK;

badOptionMsg:
  badOptionMsg:

    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
	"bad option \"%s\": must be %s",
	TclGetString(objv[i]), syntax)
	    "bad option \"%s\": must be %s",
	    TclGetString(objv[i]), syntax));
    );

badOption:
  badOption:

    Tcl_SetErrorCode(interp, "CLOCK", "badOption",
	    (i < objc) ? TclGetString(objv[i]) : (char *)NULL, (char *)NULL);

    return TCL_ERROR;
}

/*----------------------------------------------------------------------
 *
 * ClockFormatObjCmd -- , clock format --
 *
3550
3551
3552
3553
3554
3555
3556
3557

3558
3559
3560
3561
3562
3563
3564
3565
3566
3567



3568
3569
3570

3571
3572
3573
3574
3575
3576
3577
3511
3512
3513
3514
3515
3516
3517

3518
3519
3520
3521
3522
3523
3524
3525



3526
3527
3528
3529
3530

3531
3532
3533
3534
3535
3536
3537
3538







-
+







-
-
-
+
+
+


-
+







 *	None.
 *
 *----------------------------------------------------------------------
 */

int
ClockFormatObjCmd(
    void *clientData,	/* Client data containing literal pool */
    void *clientData,		/* Client data containing literal pool */
    Tcl_Interp *interp,		/* Tcl interpreter */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[])	/* Parameter values */
{
    ClockClientData *dataPtr = (ClockClientData *)clientData;

    static const char *syntax = "clock format clockval|-now "
	"?-format string? "
	"?-gmt boolean? "
	"?-locale LOCALE? ?-timezone ZONE?";
	    "?-format string? "
	    "?-gmt boolean? "
	    "?-locale LOCALE? ?-timezone ZONE?";
    int ret;
    ClockFmtScnCmdArgs opts;	/* Format, locale, timezone and base */
    DateFormat	    dateFmt;	/* Common structure used for formatting */
    DateFormat dateFmt;		/* Common structure used for formatting */

    /* even number of arguments */
    if ((objc & 1) == 1) {
	Tcl_WrongNumArgs(interp, 0, objv, syntax);
	Tcl_SetErrorCode(interp, "CLOCK", "wrongNumArgs", (char *)NULL);
	return TCL_ERROR;
    }
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601

3602
3603
3604
3605
3606

3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3552
3553
3554
3555
3556
3557
3558

3559
3560

3561

3562



3563



3564
3565
3566
3567
3568
3569
3570







-


-
+
-

-
-
-
+
-
-
-








    /* Default format */
    if (opts.formatObj == NULL) {
	opts.formatObj = dataPtr->literals[LIT__DEFAULT_FORMAT];
    }

    /* Use compiled version of Format - */

    ret = ClockFormat(&dateFmt, &opts);

done:
  done:

    TclUnsetObjRef(dateFmt.date.tzName);

    if (ret != TCL_OK) {
	return ret;
    return ret;
    }

    return TCL_OK;
}

/*----------------------------------------------------------------------
 *
 * ClockScanObjCmd -- , clock scan --
 *
 *	This function is invoked to process the Tcl "clock scan" command.
3627
3628
3629
3630
3631
3632
3633
3634

3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647


3648
3649
3650
3651
3652
3653
3654
3581
3582
3583
3584
3585
3586
3587

3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599


3600
3601
3602
3603
3604
3605
3606
3607
3608







-
+











-
-
+
+







 *	None.
 *
 *----------------------------------------------------------------------
 */

int
ClockScanObjCmd(
    void *clientData,	/* Client data containing literal pool */
    void *clientData,		/* Client data containing literal pool */
    Tcl_Interp *interp,		/* Tcl interpreter */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[])	/* Parameter values */
{
    static const char *syntax = "clock scan string "
	    "?-base seconds? "
	    "?-format string? "
	    "?-gmt boolean? "
	    "?-locale LOCALE? ?-timezone ZONE? ?-validate boolean?";
    int ret;
    ClockFmtScnCmdArgs opts;	/* Format, locale, timezone and base */
    DateInfo	    yy;		/* Common structure used for parsing */
    DateInfo	   *info = &yy;
    DateInfo yy;		/* Common structure used for parsing */
    DateInfo *info = &yy;

    /* even number of arguments */
    if ((objc & 1) == 1) {
	Tcl_WrongNumArgs(interp, 0, objv, syntax);
	Tcl_SetErrorCode(interp, "CLOCK", "wrongNumArgs", (char *)NULL);
	return TCL_ERROR;
    }
3669
3670
3671
3672
3673
3674
3675
3676


3677
3678
3679


3680
3681
3682
3683
3684
3685
3686

3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702


3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718

3719
3720
3721
3722
3723
3724
3725

3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3623
3624
3625
3626
3627
3628
3629

3630
3631
3632


3633
3634
3635
3636
3637
3638
3639


3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654


3655
3656

3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670

3671
3672
3673
3674
3675
3676
3677

3678

3679

3680
3681
3682

3683
3684
3685
3686
3687
3688
3689







-
+
+

-
-
+
+





-
-
+














-
-
+
+
-














-
+






-
+
-

-



-







    /* seconds are in localSeconds (relative base date), so reset time here */
    yyHour = yyMinutes = yySeconds = yySecondOfDay = 0; yyMeridian = MER24;

    /* If free scan */
    if (opts.formatObj == NULL) {
	/* Use compiled version of FreeScan - */

	/* [SB] TODO: Perhaps someday we'll localize the legacy code. Right now, it's not localized. */
	/* [SB] TODO: Perhaps someday we'll localize the legacy code. Right now,
	 * it's not localized. */
	if (opts.localeObj != NULL) {
	    Tcl_SetObjResult(interp,
		Tcl_NewStringObj("legacy [clock scan] does not support -locale", -1));
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "legacy [clock scan] does not support -locale", -1));
	    Tcl_SetErrorCode(interp, "CLOCK", "flagWithLegacyFormat", (char *)NULL);
	    ret = TCL_ERROR;
	    goto done;
	}
	ret = ClockFreeScan(&yy, objv[1], &opts);
    }
    else {
    } else {
	/* Use compiled version of Scan - */

	ret = ClockScan(&yy, objv[1], &opts);
    }

    if (ret != TCL_OK) {
	goto done;
    }

    /*
     * If no GMT and not free-scan (where valid stage 1 is done in-between),
     * validate with stage 1 before local time conversion, otherwise it may
     * adjust date/time tokens to valid values
     */
    if ( (opts.flags & CLF_VALIDATE_S1) &&
	 info->flags & (CLF_ASSEMBLE_SECONDS|CLF_LOCALSEC)
    if ((opts.flags & CLF_VALIDATE_S1)
	    && info->flags & (CLF_ASSEMBLE_SECONDS|CLF_LOCALSEC)) {
    ) {
	ret = ClockValidDate(&yy, &opts, CLF_VALIDATE_S1);
	if (ret != TCL_OK) {
	    goto done;
	}
    }

    /* Convert date info structure into UTC seconds */

    ret = ClockScanCommit(&yy, &opts);
    if (ret != TCL_OK) {
	goto done;
    }

    /* Apply remaining validation rules, if expected */
    if ( (opts.flags & CLF_VALIDATE) ) {
    if ((opts.flags & CLF_VALIDATE)) {
	ret = ClockValidDate(&yy, &opts, opts.flags & CLF_VALIDATE);
	if (ret != TCL_OK) {
	    goto done;
	}
    }

done:
  done:

    TclUnsetObjRef(yy.date.tzName);

    if (ret != TCL_OK) {
	return ret;
    }

    Tcl_SetObjResult(interp, Tcl_NewWideIntObj(yy.date.seconds));
    return TCL_OK;
}

/*----------------------------------------------------------------------
 *
 * ClockScanCommit --
3747
3748
3749
3750
3751
3752
3753
3754

3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765



3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777

3778
3779

3780
3781
3782

3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794



3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828

3829
3830
3831
3832
3833
3834
3835
3836
3837

3838
3839
3840
3841
3842
3843





3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855





3856
3857
3858
3859
3860
3861





3862
3863
3864
3865
3866
3867
3868
3869



3870
3871
3872
3873
3874
3875
3876




3877
3878
3879
3880
3881
3882


3883
3884
3885



3886

3887
3888



3889
3890
3891
3892
3893
3894
3895





3896
3897
3898
3899
3900
3901

3902
3903
3904
3905
3906
3907
3908



3909
3910
3911
3912
3913
3914
3915




3916
3917
3918
3919




3920
3921
3922
3923




3924
3925
3926
3927
3928
3929
3930
3697
3698
3699
3700
3701
3702
3703

3704
3705
3706
3707
3708
3709
3710





3711
3712
3713

3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726

3727
3728
3729

3730
3731
3732
3733
3734
3735
3736
3737
3738
3739



3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754

3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774

3775
3776
3777
3778
3779
3780
3781
3782
3783

3784
3785





3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799



3800
3801
3802
3803
3804
3805
3806
3807



3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819

3820
3821
3822
3823
3824
3825
3826
3827


3828
3829
3830
3831
3832
3833
3834
3835


3836
3837



3838
3839
3840
3841
3842


3843
3844
3845
3846
3847
3848
3849



3850
3851
3852
3853
3854
3855
3856
3857
3858
3859

3860
3861
3862
3863
3864
3865
3866

3867
3868
3869
3870
3871
3872
3873
3874


3875
3876
3877
3878
3879
3880


3881
3882
3883
3884
3885
3886


3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897







-
+






-
-
-
-
-
+
+
+
-











+

-
+


-
+









-
-
-
+
+
+












-




















-
+








-
+

-
-
-
-
-
+
+
+
+
+









-
-
-
+
+
+
+
+



-
-
-
+
+
+
+
+







-
+
+
+





-
-
+
+
+
+




-
-
+
+
-
-
-
+
+
+

+
-
-
+
+
+




-
-
-
+
+
+
+
+





-
+






-
+
+
+





-
-
+
+
+
+


-
-
+
+
+
+


-
-
+
+
+
+







 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
ClockScanCommit(
    DateInfo  *info,	/* Clock scan info structure */
    DateInfo *info,		/* Clock scan info structure */
    ClockFmtScnCmdArgs *opts)	/* Format, locale, timezone and base */
{
    /* If needed assemble julianDay using year, month, etc. */
    if (info->flags & CLF_ASSEMBLE_JULIANDAY) {
	if ((info->flags & CLF_ISO8601WEAK)) {
	    GetJulianDayFromEraYearWeekDay(&yydate, GREGORIAN_CHANGE_DATE);
	}
	else
	if ( !(info->flags & CLF_DAYOFYEAR) /* no day of year */
	   || (info->flags & (CLF_DAYOFMONTH|CLF_MONTH)) /* yymmdd over yyddd */
		== (CLF_DAYOFMONTH|CLF_MONTH)
	} else if (!(info->flags & CLF_DAYOFYEAR) /* no day of year */
		|| (info->flags & (CLF_DAYOFMONTH|CLF_MONTH)) /* yymmdd over yyddd */
		== (CLF_DAYOFMONTH|CLF_MONTH)) {
	) {
	    GetJulianDayFromEraYearMonthDay(&yydate, GREGORIAN_CHANGE_DATE);
	} else {
	    GetJulianDayFromEraYearDay(&yydate, GREGORIAN_CHANGE_DATE);
	}
	info->flags |= CLF_ASSEMBLE_SECONDS;
	info->flags &= ~CLF_ASSEMBLE_JULIANDAY;
    }

    /* some overflow checks */
    if (info->flags & CLF_JULIANDAY) {
	ClockClientData *dataPtr = (ClockClientData *)opts->clientData;

	double curJDN = (double)yydate.julianDay
	    + ((double)yySecondOfDay - SECONDS_PER_DAY/2) / SECONDS_PER_DAY;
		+ ((double)yySecondOfDay - SECONDS_PER_DAY/2) / SECONDS_PER_DAY;
	if (curJDN > dataPtr->maxJDN) {
	    Tcl_SetObjResult(opts->interp, Tcl_NewStringObj(
		"requested date too large to represent", -1));
		    "requested date too large to represent", -1));
	    Tcl_SetErrorCode(opts->interp, "CLOCK", "dateTooLarge", (char *)NULL);
	    return TCL_ERROR;
	}
    }

    /* Local seconds to UTC (stored in yydate.seconds) */

    if (info->flags & (CLF_ASSEMBLE_SECONDS)) {
	yydate.localSeconds =
	    -210866803200LL
	    + ( SECONDS_PER_DAY * yydate.julianDay )
	    + ( yySecondOfDay % SECONDS_PER_DAY );
		-210866803200LL
		+ (SECONDS_PER_DAY * yydate.julianDay)
		+ (yySecondOfDay % SECONDS_PER_DAY);
    }

    if (info->flags & (CLF_ASSEMBLE_SECONDS|CLF_LOCALSEC)) {
	if (ConvertLocalToUTC(opts->clientData, opts->interp, &yydate,
		opts->timezoneObj, GREGORIAN_CHANGE_DATE) != TCL_OK) {
	    return TCL_ERROR;
	}
    }

    /* Increment UTC seconds with relative time */

    yydate.seconds += yyRelSeconds;

    return TCL_OK;
}

/*----------------------------------------------------------------------
 *
 * ClockValidDate --
 *
 *	Validate date info structure for wrong data (e. g. out of ranges).
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
ClockValidDate(
    DateInfo  *info,	/* Clock scan info structure */
    DateInfo *info,		/* Clock scan info structure */
    ClockFmtScnCmdArgs *opts,	/* Scan options */
    int stage)			/* Stage to validate (1, 2 or 3 for both) */
{
    const char *errMsg = "", *errCode = "";
    TclDateFields temp;
    int tempCpyFlg = 0;
    ClockClientData *dataPtr = (ClockClientData *)opts->clientData;

    #if 0
#if 0
    printf("yyMonth %d, yyDay %d, yyDayOfYear %d, yyHour %d, yyMinutes %d, yySeconds %d, "
	   "yySecondOfDay %d, sec %d, daySec %d, tzOffset %d\n",
	  yyMonth, yyDay, yydate.dayOfYear, yyHour, yyMinutes, yySeconds,
	  yySecondOfDay, (int)yydate.localSeconds, (int)(yydate.localSeconds % SECONDS_PER_DAY),
	  yydate.tzOffset);
    #endif
	    "yySecondOfDay %d, sec %d, daySec %d, tzOffset %d\n",
	    yyMonth, yyDay, yydate.dayOfYear, yyHour, yyMinutes, yySeconds,
	    yySecondOfDay, (int)yydate.localSeconds, (int)(yydate.localSeconds % SECONDS_PER_DAY),
	    yydate.tzOffset);
#endif

    if (!(stage & CLF_VALIDATE_S1) || !(opts->flags & CLF_VALIDATE_S1)) {
	goto stage_2;
    }
    opts->flags &= ~CLF_VALIDATE_S1; /* stage 1 is done */

    /* first year (used later in hath / daysInPriorMonths) */
    if ((info->flags & (CLF_YEAR|CLF_ISO8601YEAR))) {
	if ((info->flags & CLF_ISO8601YEAR)) {
	    if ( yydate.iso8601Year < dataPtr->validMinYear
	      || yydate.iso8601Year > dataPtr->validMaxYear ) {
		errMsg = "invalid iso year"; errCode = "iso year"; goto error;
	    if (yydate.iso8601Year < dataPtr->validMinYear
		    || yydate.iso8601Year > dataPtr->validMaxYear) {
		errMsg = "invalid iso year";
		errCode = "iso year";
		goto error;
	    }
	}
	if (info->flags & CLF_YEAR) {
	    if ( yyYear < dataPtr->validMinYear
	      || yyYear > dataPtr->validMaxYear ) {
		errMsg = "invalid year"; errCode = "year"; goto error;
	    if (yyYear < dataPtr->validMinYear
		    || yyYear > dataPtr->validMaxYear) {
		errMsg = "invalid year";
		errCode = "year";
		goto error;
	    }
	} else if ((info->flags & CLF_ISO8601YEAR)) {
	    yyYear = yydate.iso8601Year; /* used to recognize leap */
	}
	if ((info->flags & (CLF_ISO8601YEAR|CLF_YEAR))
		== (CLF_ISO8601YEAR|CLF_YEAR)) {
	    if (yyYear != yydate.iso8601Year) {
		errMsg = "ambiguous year"; errCode = "year"; goto error;
		errMsg = "ambiguous year";
		errCode = "year";
		goto error;
	    }
	}
    }
    /* and month (used later in hath) */
    if (info->flags & CLF_MONTH) {
	if ( yyMonth < 1 || yyMonth > 12 ) {
	    errMsg = "invalid month"; errCode = "month"; goto error;
	if (yyMonth < 1 || yyMonth > 12) {
	    errMsg = "invalid month";
	    errCode = "month";
	    goto error;
	}
    }
    /* day of month */
    if (info->flags & (CLF_DAYOFMONTH|CLF_DAYOFWEEK)) {
	if ( yyDay < 1 || yyDay > 31 ) {
	    errMsg = "invalid day"; errCode = "day"; goto error;
	if (yyDay < 1 || yyDay > 31) {
	    errMsg = "invalid day";
	}
	else
	if ( (info->flags & CLF_MONTH) ) {
	    errCode = "day";
	    goto error;
	} else if ((info->flags & CLF_MONTH)) {
	    const int *h = hath[IsGregorianLeapYear(&yydate)];

	    if ( yyDay > h[yyMonth-1] ) {
		errMsg = "invalid day"; goto error;
	    if (yyDay > h[yyMonth - 1]) {
		errMsg = "invalid day";
		goto error;
	    }
	}
    }
    if (info->flags & CLF_DAYOFYEAR) {
	if ( yydate.dayOfYear < 1
	  || yydate.dayOfYear > daysInPriorMonths[IsGregorianLeapYear(&yydate)][12] ) {
	    errMsg = "invalid day of year"; errCode = "day of year"; goto error;
	if (yydate.dayOfYear < 1
		|| yydate.dayOfYear > daysInPriorMonths[IsGregorianLeapYear(&yydate)][12]) {
	    errMsg = "invalid day of year";
	    errCode = "day of year";
	    goto error;
	}
    }

    /* mmdd !~ ddd */
    if ((info->flags & (CLF_DAYOFYEAR|CLF_DAYOFMONTH|CLF_MONTH))
		== (CLF_DAYOFYEAR|CLF_DAYOFMONTH|CLF_MONTH)) {
	    == (CLF_DAYOFYEAR|CLF_DAYOFMONTH|CLF_MONTH)) {
	if (!tempCpyFlg) {
	    memcpy(&temp, &yydate, sizeof(temp));
	    tempCpyFlg = 1;
	}
	GetJulianDayFromEraYearDay(&temp, GREGORIAN_CHANGE_DATE);
	if (temp.julianDay != yydate.julianDay) {
	    errMsg = "ambiguous day"; errCode = "day"; goto error;
	    errMsg = "ambiguous day";
	    errCode = "day";
	    goto error;
	}
    }

    if (info->flags & CLF_TIME) {
	/* hour */
	if ( yyHour < 0 || yyHour > ((yyMeridian == MER24) ? 23 : 12) ) {
	    errMsg = "invalid time (hour)"; errCode = "hour"; goto error;
	if (yyHour < 0 || yyHour > ((yyMeridian == MER24) ? 23 : 12)) {
	    errMsg = "invalid time (hour)";
	    errCode = "hour";
	    goto error;
	}
	/* minutes */
	if ( yyMinutes < 0 || yyMinutes > 59 ) {
	    errMsg = "invalid time (minutes)"; errCode = "minutes"; goto error;
	if (yyMinutes < 0 || yyMinutes > 59) {
	    errMsg = "invalid time (minutes)";
	    errCode = "minutes";
	    goto error;
	}
	/* oldscan could return secondOfDay (parsedTime) -1 by invalid time (ex.: 25:00:00) */
	if ( yySeconds < 0 || yySeconds > 59 || yySecondOfDay <= -1 ) {
	    errMsg = "invalid time"; errCode = "seconds"; goto error;
	if (yySeconds < 0 || yySeconds > 59 || yySecondOfDay <= -1) {
	    errMsg = "invalid time";
	    errCode = "seconds";
	    goto error;
	}
    }

    if (!(stage & CLF_VALIDATE_S2) || !(opts->flags & CLF_VALIDATE_S2)) {
	return TCL_OK;
    }
    opts->flags &= ~CLF_VALIDATE_S2; /* stage 2 is done */
3940
3941
3942
3943
3944
3945
3946
3947

3948
3949


3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961



3962
3963
3964
3965
3966
3967
3968
3969


3970
3971
3972
3973
3974
3975
3976
3907
3908
3909
3910
3911
3912
3913

3914
3915

3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928

3929
3930
3931
3932
3933
3934
3935
3936
3937


3938
3939
3940
3941
3942
3943
3944
3945
3946







-
+

-
+
+











-
+
+
+






-
-
+
+







    if (info->flags & CLF_TIME) {
	/*
	 * we don't need to do the backwards time-conversion (UTC to local) and
	 * compare results, because the after conversion (local to UTC) we
	 * should have valid localSeconds (was not invalidated to TCL_INV_SECONDS),
	 * so if it was invalidated - invalid time, outside the time-zone (in DST-hole)
	 */
	if ( yydate.localSeconds == TCL_INV_SECONDS ) {
	if (yydate.localSeconds == TCL_INV_SECONDS) {
	    errMsg = "invalid time (does not exist in this time-zone)";
	    errCode = "out-of-time"; goto error;
	    errCode = "out-of-time";
	    goto error;
	}
    }

    /* day of week */
    if (info->flags & CLF_DAYOFWEEK) {
	if (!tempCpyFlg) {
	    memcpy(&temp, &yydate, sizeof(temp));
	    tempCpyFlg = 1;
	}
	GetYearWeekDay(&temp, GREGORIAN_CHANGE_DATE);
	if (temp.dayOfWeek != yyDayOfWeek) {
	    errMsg = "invalid day of week"; errCode = "day of week"; goto error;
	    errMsg = "invalid day of week";
	    errCode = "day of week";
	    goto error;
	}
    }

    return TCL_OK;

  error:
    Tcl_SetObjResult(opts->interp,
	Tcl_ObjPrintf("unable to convert input string: %s", errMsg));
    Tcl_SetObjResult(opts->interp, Tcl_ObjPrintf(
	    "unable to convert input string: %s", errMsg));
    Tcl_SetErrorCode(opts->interp, "CLOCK", "invInpStr", errCode, (char *)NULL);
    return TCL_ERROR;
}

/*----------------------------------------------------------------------
 *
 * ClockFreeScan --
3984
3985
3986
3987
3988
3989
3990
3991

3992
3993
3994
3995
3996
3997

3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013

4014
4015
4016

4017
4018
4019
4020
4021
4022
4023
3954
3955
3956
3957
3958
3959
3960

3961
3962
3963
3964
3965
3966

3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986

3987
3988
3989
3990
3991
3992
3993
3994







-
+





-
+
















+


-
+







 *	None.
 *
 *----------------------------------------------------------------------
 */

int
ClockFreeScan(
    DateInfo	       *info,	/* Date fields used for parsing & converting
    DateInfo *info,		/* Date fields used for parsing & converting
				 * simultaneously a yy-parse structure of the
				 * TclClockFreeScan */
    Tcl_Obj *strObj,		/* String containing the time to scan */
    ClockFmtScnCmdArgs *opts)	/* Command options */
{
    Tcl_Interp	    *interp =  opts->interp;
    Tcl_Interp *interp = opts->interp;
    ClockClientData *dataPtr = (ClockClientData *)opts->clientData;

    int ret = TCL_ERROR;

    /*
     * Parse the date. The parser will fill a structure "info" with date,
     * time, time zone, relative month/day/seconds, relative weekday, ordinal
     * month.
     * Notice that many yy-defines point to values in the "info" or "date"
     * structure, e. g. yySecondOfDay -> info->date.secondOfDay or
     *			yyMonth -> info->date.month (same as yydate.month)
     */
    yyInput = TclGetString(strObj);

    if (TclClockFreeScan(interp, info) != TCL_OK) {
	Tcl_Obj *msg;

	TclNewObj(msg);
	Tcl_AppendPrintfToObj(msg, "unable to convert date-time string \"%s\": %s",
	    TclGetString(strObj), Tcl_GetString(Tcl_GetObjResult(interp)));
		TclGetString(strObj), Tcl_GetString(Tcl_GetObjResult(interp)));
	Tcl_SetObjResult(interp, msg);
	goto done;
    }

    /*
     * If the caller supplied a date in the string, update the date with
     * the value. If the caller didn't specify a time with the date, default to
4042
4043
4044
4045
4046
4047
4048

4049
4050

4051
4052
4053
4054
4055
4056
4057
4058
4059

4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074

4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089

4090
4091

4092
4093
4094
4095

4096
4097

4098
4099

4100
4101
4102
4103
4104

4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116

4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137

4138
4139
4140
4141
4142
4143
4144
4145
4146

4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4013
4014
4015
4016
4017
4018
4019
4020
4021

4022
4023
4024
4025
4026
4027
4028
4029
4030

4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045

4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058



4059
4060

4061
4062



4063
4064

4065


4066

4067
4068


4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080

4081

4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100

4101
4102

4103
4104
4105
4106
4107
4108

4109

4110

4111
4112
4113
4114
4115
4116
4117







+

-
+








-
+














-
+












-
-
-
+

-
+

-
-
-
+

-
+
-
-
+
-


-
-
+











-
+
-



















-
+

-






-
+
-

-








    if (info->flags & CLF_ZONE) {
	if (yyTimezone || !yyDSTmode) {
	    /* Real time zone from numeric zone */
	    Tcl_Obj *tzObjStor = NULL;
	    int minEast = -yyTimezone;
	    int dstFlag = 1 - yyDSTmode;

	    tzObjStor = ClockFormatNumericTimeZone(
				60 * minEast + 3600 * dstFlag);
		    60 * minEast + 3600 * dstFlag);
	    Tcl_IncrRefCount(tzObjStor);

	    opts->timezoneObj = ClockSetupTimeZone(dataPtr, interp, tzObjStor);

	    Tcl_DecrRefCount(tzObjStor);
	} else {
	    /* simplest case - GMT / UTC */
	    opts->timezoneObj = ClockSetupTimeZone(dataPtr, interp,
		dataPtr->literals[LIT_GMT]);
		    dataPtr->literals[LIT_GMT]);
	}
	if (opts->timezoneObj == NULL) {
	    goto done;
	}

	// TclSetObjRef(yydate.tzName, opts->timezoneObj);

	info->flags |= CLF_ASSEMBLE_SECONDS;
    }

    /*
     * For freescan apply validation rules (stage 1) before mixed with
     * relative time (otherwise always valid recalculated date & time).
     */
    if ( (opts->flags & CLF_VALIDATE) ) {
    if ((opts->flags & CLF_VALIDATE)) {
	if (ClockValidDate(info, opts, CLF_VALIDATE_S1) != TCL_OK) {
	    goto done;
	}
    }

    /*
     * Assemble date, time, zone into seconds-from-epoch
     */

    if ((info->flags & (CLF_TIME|CLF_HAVEDATE)) == CLF_HAVEDATE) {
	yySecondOfDay = 0;
	info->flags |= CLF_ASSEMBLE_SECONDS;
    }
    else
    if (info->flags & CLF_TIME) {
    } else if (info->flags & CLF_TIME) {
	yySecondOfDay = ToSeconds(yyHour, yyMinutes,
			    yySeconds, yyMeridian);
		yySeconds, yyMeridian);
	info->flags |= CLF_ASSEMBLE_SECONDS;
    }
    else
    if ( (info->flags & (CLF_DAYOFWEEK|CLF_HAVEDATE)) == CLF_DAYOFWEEK
    } else if ((info->flags & (CLF_DAYOFWEEK|CLF_HAVEDATE)) == CLF_DAYOFWEEK
	    || (info->flags & CLF_ORDINALMONTH)
	    || ( (info->flags & CLF_RELCONV)
	    || ((info->flags & CLF_RELCONV)
		&& ( yyRelMonth != 0
		     || yyRelDay != 0 ) )
	    && (yyRelMonth != 0 || yyRelDay != 0))) {
    ) {
	yySecondOfDay = 0;
	info->flags |= CLF_ASSEMBLE_SECONDS;
    }
    else {
    } else {
	yySecondOfDay = yydate.localSeconds % SECONDS_PER_DAY;
    }

    /*
     * Do relative times
     */

    ret = ClockCalcRelTime(info);

    /* Free scanning completed - date ready */

done:
  done:

    return ret;
}

/*----------------------------------------------------------------------
 *
 * ClockCalcRelTime --
 *
 *	Used for calculating of relative times.
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
int
ClockCalcRelTime(
    DateInfo	       *info)	/* Date fields used for converting */
    DateInfo *info)		/* Date fields used for converting */
{

    int prevDayOfWeek = yyDayOfWeek;	/* preserve unchanged day of week */

    /*
     * Because some calculations require in-between conversion of the
     * julian day, we can repeat this processing multiple times
     */
repeat_rel:
  repeat_rel:

    if (info->flags & CLF_RELCONV) {

	/*
	 * Relative conversion normally possible in UTC time only, because
	 * of possible wrong local time increment if ignores in-between DST-hole.
	 * (see test-cases clock-34.53, clock-34.54).
	 * So increment date in julianDay, but time inside day in UTC (seconds).
	 */

4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4149
4150
4151
4152
4153
4154
4155

4156
4157
4158
4159
4160
4161
4162
4163
4164

4165
4166
4167
4168
4169
4170
4171
4172
4173
4174

4175
4176
4177
4178
4179
4180
4181







-









-










-







	    info->flags |= CLF_ASSEMBLE_JULIANDAY|CLF_ASSEMBLE_SECONDS;

	    yyRelMonth = 0;
	}

	/* add days (or other parts aligned to days) */
	if (yyRelDay) {

	    /* assemble julianDay using new year, month, etc. */
	    if (info->flags & CLF_ASSEMBLE_JULIANDAY) {
		GetJulianDayFromEraYearMonthDay(&yydate, GREGORIAN_CHANGE_DATE);
		info->flags &= ~CLF_ASSEMBLE_JULIANDAY;
	    }
	    yydate.julianDay += yyRelDay;

	    /* julianDay was changed, on demand (lazy) extract year, month, etc. again */
	    info->flags |= CLF_ASSEMBLE_DATE|CLF_ASSEMBLE_SECONDS;

	    yyRelDay = 0;
	}

	/* relative time (seconds), if exceeds current date, do the day conversion and
	 * leave rest of the increment in yyRelSeconds to add it hereafter in UTC seconds */
	if (yyRelSeconds) {
	    Tcl_WideInt newSecs = yySecondOfDay + yyRelSeconds;

	    /* if seconds increment outside of current date, increment day */
	    if (newSecs / SECONDS_PER_DAY != yySecondOfDay / SECONDS_PER_DAY) {

		yyRelDay += newSecs / SECONDS_PER_DAY;
		yySecondOfDay = 0;
		yyRelSeconds = newSecs % SECONDS_PER_DAY;

		goto repeat_rel;
	    }
	}
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283

4284
4285
4286
4287
4288
4289
4290
4222
4223
4224
4225
4226
4227
4228

4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239

4240
4241
4242
4243
4244
4245
4246
4247







-











-
+







    }

    /*
     * Do relative weekday
     */

    if ((info->flags & (CLF_DAYOFWEEK|CLF_HAVEDATE)) == CLF_DAYOFWEEK) {

	/* restore scanned day of week */
	yyDayOfWeek = prevDayOfWeek;

	/* if needed assemble julianDay now */
	if (info->flags & CLF_ASSEMBLE_JULIANDAY) {
	    GetJulianDayFromEraYearMonthDay(&yydate, GREGORIAN_CHANGE_DATE);
	    info->flags &= ~CLF_ASSEMBLE_JULIANDAY;
	}

	yydate.isBce = 0;
	yydate.julianDay = WeekdayOnOrBefore(yyDayOfWeek, yydate.julianDay + 6)
		    + 7 * yyDayOrdinal;
		+ 7 * yyDayOrdinal;
	if (yyDayOrdinal > 0) {
	    yydate.julianDay -= 7;
	}
	info->flags |= CLF_ASSEMBLE_DATE|CLF_ASSEMBLE_SECONDS;
    }

    return TCL_OK;
4321
4322
4323
4324
4325
4326
4327

4328
4329
4330
4331
4332
4333
4334
4335
4336
4337

4338
4339
4340
4341
4342
4343
4344

4345
4346
4347
4348
4349
4350
4351
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302

4303
4304
4305
4306
4307
4308
4309
4310







+










+






-
+







	offs = 5 + offs;
    }
    offs += 7 * weeks;

    /* resulting day of week */
    {
	int day = (offs % 7);

	/* compiler fix for negative offs - wrap (0, -1) -> (-1, 6) */
	if (day < 0) {
	    day = 7 + day;
	}
	resDayOfWeek = dayOfWeek + day;
    }

    /* adjust if we start from a weekend */
    if (dayOfWeek > 5) {
	int adj = 5 - dayOfWeek;

	offs += adj;
	resDayOfWeek += adj;
    }

    /* adjust if we end up on a weekend */
    if (resDayOfWeek > 5) {
       offs += 2;
	offs += 2;
    }

    return offs;
}



4388
4389
4390
4391
4392
4393
4394
4395

4396
4397
4398
4399
4400
4401
4402


4403
4404
4405
4406
4407


4408
4409
4410
4411
4412
4413
4414
4347
4348
4349
4350
4351
4352
4353

4354
4355
4356
4357
4358
4359


4360
4361
4362
4363
4364


4365
4366
4367
4368
4369
4370
4371
4372
4373







-
+





-
-
+
+



-
-
+
+







 *   than 31 days.
 *
 *----------------------------------------------------------------------
 */

int
ClockAddObjCmd(
    void *clientData,	/* Client data containing literal pool */
    void *clientData,		/* Client data containing literal pool */
    Tcl_Interp *interp,		/* Tcl interpreter */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[])	/* Parameter values */
{
    static const char *syntax = "clock add clockval|-now ?number units?..."
	"?-gmt boolean? "
	"?-locale LOCALE? ?-timezone ZONE?";
	    "?-gmt boolean? "
	    "?-locale LOCALE? ?-timezone ZONE?";
    ClockClientData *dataPtr = (ClockClientData *)clientData;
    int ret;
    ClockFmtScnCmdArgs opts;	/* Format, locale, timezone and base */
    DateInfo	    yy;		/* Common structure used for parsing */
    DateInfo	   *info = &yy;
    DateInfo yy;		/* Common structure used for parsing */
    DateInfo *info = &yy;

    /* add "week" to units also (because otherwise ambiguous) */
    static const char *const units[] = {
	"years",	"months",	    "week",	    "weeks",
	"days",		"weekdays",
	"hours",	"minutes",	    "seconds",
	NULL
4455
4456
4457
4458
4459
4460
4461
4462

4463
4464
4465
4466
4467
4468


4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489







4490
4491
4492
4493
4494
4495
4496
4497
4498
4414
4415
4416
4417
4418
4419
4420

4421
4422
4423
4424
4425


4426
4427

4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440







4441
4442
4443
4444
4445
4446
4447


4448
4449
4450
4451
4452
4453
4454







-
+




-
-
+
+
-













-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-








    for (i = 2; i < objc; i+=2) {
	/* bypass not integers (options, allready processed above in ClockParseFmtScnArgs) */
	if (TclGetWideIntFromObj(NULL, objv[i], &offs) != TCL_OK) {
	    continue;
	}
	/* get unit */
	if (Tcl_GetIndexFromObj(interp, objv[i+1], units, "unit", 0,
	if (Tcl_GetIndexFromObj(interp, objv[i + 1], units, "unit", 0,
		&unitIndex) != TCL_OK) {
	    goto done;
	}
	if (TclHasInternalRep(objv[i], &tclBignumType)
	    || offs > (unitIndex < CLC_ADD_HOURS ? 0x7fffffff : TCL_MAX_SECONDS)
	    || offs < (unitIndex < CLC_ADD_HOURS ? -0x7fffffff : TCL_MIN_SECONDS)
		|| offs > (unitIndex < CLC_ADD_HOURS ? 0x7fffffff : TCL_MAX_SECONDS)
		|| offs < (unitIndex < CLC_ADD_HOURS ? -0x7fffffff : TCL_MIN_SECONDS)) {
	) {
	    Tcl_SetObjResult(interp, dataPtr->literals[LIT_INTEGER_VALUE_TOO_LARGE]);
	    goto done;
	}

	/* nothing to do if zero quantity */
	if (!offs) {
	    continue;
	}

	/* if in-between conversion needed (already have relative date/time),
	 * correct date info, because the date may be changed,
	 * so refresh it now */

	if ( (info->flags & CLF_RELCONV)
	  && ( unitIndex == CLC_ADD_WEEKDAYS
	    /* some months can be shorter as another */
	    || yyRelMonth || yyRelDay
	    /* day changed */
	    || yySeconds + yyRelSeconds > SECONDS_PER_DAY
	    || yySeconds + yyRelSeconds < 0
	if ((info->flags & CLF_RELCONV)
		&& (unitIndex == CLC_ADD_WEEKDAYS
		/* some months can be shorter as another */
		|| yyRelMonth || yyRelDay
		/* day changed */
		|| yySeconds + yyRelSeconds > SECONDS_PER_DAY
		|| yySeconds + yyRelSeconds < 0)) {
	  )
	) {
	    if (ClockCalcRelTime(info) != TCL_OK) {
		goto done;
	    }
	}

	/* process increment by offset + unit */
	info->flags |= CLF_RELCONV;
4538
4539
4540
4541
4542
4543
4544
4545

4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4494
4495
4496
4497
4498
4499
4500

4501

4502

4503
4504
4505

4506
4507
4508
4509
4510
4511
4512







-
+
-

-



-







	}
    }

    /* Convert date info structure into UTC seconds */

    ret = ClockScanCommit(&yy, &opts);

done:
  done:

    TclUnsetObjRef(yy.date.tzName);

    if (ret != TCL_OK) {
	return ret;
    }

    Tcl_SetObjResult(interp, Tcl_NewWideIntObj(yy.date.seconds));
    return TCL_OK;
}

/*----------------------------------------------------------------------
 *
 * ClockSecondsObjCmd -
4629
4630
4631
4632
4633
4634
4635
4636

4637
4638
4639
4640
4641
4642
4643
4582
4583
4584
4585
4586
4587
4588

4589
4590
4591
4592
4593
4594
4595
4596







-
+







    InterpState *statePtr;

    if (objc == 1) {
	/* wrong # args : */
	return Tcl_CatchObjCmd(NULL, interp, objc, objv);
    }

    statePtr = (InterpState *)Tcl_SaveInterpState(interp, 0);
    statePtr = (InterpState *) Tcl_SaveInterpState(interp, 0);
    if (!statePtr->errorInfo) {
	/* todo: avoid traced get of errorInfo here */
	TclInitObjRef(statePtr->errorInfo,
		Tcl_ObjGetVar2(interp, iPtr->eiVar, NULL, 0));
	flags |= ERR_LEGACY_COPY;
    }
    if (!statePtr->errorCode) {