fnc

Check-in Differences
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Difference From 0.4 To 0.5

2021-11-03 11:34
Bump version number: 0.6 (check-in: 9d73a79fa8 user: mark tags: trunk)
2021-11-03 11:28
CHANGES for 0.5 (check-in: 02e93d1924 user: mark tags: trunk, 0.5)
2021-11-03 11:06
Complete move of fnc_strl{cpy,cat} to the library. (check-in: d10389ebe4 user: mark tags: trunk)
2021-10-31 13:18
Bump version number: 0.5 (check-in: b977d0e1f4 user: mark tags: trunk)
2021-10-31 12:21
CHANGES for 0.4 (check-in: 3cc00310ea user: mark tags: trunk, 0.4)
2021-10-31 11:23
Improve documentation and amend incorrect path in README. (check-in: 22126a3f58 user: mark tags: trunk)

Changes to .fossil-settings/ignore-glob.

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
9
10
11
12
13
14
15

16
17
18
19
20
21
22







-







*.res
*.sl
*.so
*~
*.vg
*.massif
*._out
Makefile
autosetup/jimsh0
config.log
config.make
bindings/cpp/Makefile
bindings/cpp/test
doc/Doxyfile
f-apps/Makefile

Changes to CHANGES.md.








1
2
3
4
5
6
7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
+
+
+
+
+
+
+







**fnc 0.5** 2021-11-03

- simplify the build system to make-only and remove autosetup (patch from sdk)
- remove invalid fsl_errno_to_rc() call and redundant alloc error check
- reduce noise on app exit by removing redundant error output
- relocate fnc_strlcpy() and fnc_strlcat() routines to the library

**fnc 0.4** 2021-10-31

- resolve database bug in the commit builder logic
- prune dead code leftover from the initial single-threaded blame implementation
- improve error handling of commands that return no records
- update in-app help with blame key bindings
- expand tree command's ability to display trees of versions with missing files

Added LICENSE.














1
2
3
4
5
6
7
8
9
10
11
12
13
+
+
+
+
+
+
+
+
+
+
+
+
+
Copyright (c) 2021 Mark Jamsek <mark@jamsek.com>

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Added Makefile.































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#
# FNC Makefile
#

# CONFIGUGRAION
CC ?=		cc
PREFIX ?=	/usr/local
MANDIR ?=	/share/man
VERSION ?=	0.5

# USED BELOW FOR PLATFORM SPECIFIC LDFLAGS
UNAME :=	$(shell uname -s)

# FLAGS NEEDED TO BUILD SQLITE3
SQLITE_CFLAGS =	${CFLAGS} -Wall -Werror -Wno-sign-compare -pedantic -std=c99 \
		-DNDEBUG=1 \
		-DSQLITE_DQS=0 \
		-DSQLITE_THREADSAFE=0 \
		-DSQLITE_DEFAULT_MEMSTATUS=0 \
		-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 \
		-DSQLITE_LIKE_DOESNT_MATCH_BLOBS \
		-DSQLITE_OMIT_DECLTYPE \
		-DSQLITE_OMIT_PROGRESS_CALLBACK \
		-DSQLITE_OMIT_SHARED_CACHE \
		-DSQLITE_OMIT_LOAD_EXTENSION \
		-DSQLITE_MAX_EXPR_DEPTH=0 \
		-DSQLITE_USE_ALLOCA \
		-DSQLITE_ENABLE_LOCKING_STYLE=0 \
		-DSQLITE_DEFAULT_FILE_FORMAT=4 \
		-DSQLITE_ENABLE_EXPLAIN_COMMENTS \
		-DSQLITE_ENABLE_FTS4 \
		-DSQLITE_ENABLE_DBSTAT_VTAB \
		-DSQLITE_ENABLE_JSON1 \
		-DSQLITE_ENABLE_FTS5 \
		-DSQLITE_ENABLE_STMTVTAB \
		-DSQLITE_HAVE_ZLIB \
		-DSQLITE_INTROSPECTION_PRAGMAS \
		-DSQLITE_ENABLE_DBPAGE_VTAB \
		-DSQLITE_TRUSTED_SCHEMA=0

# This makefile
MAKEFILE := $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))

# FLAGS NEEDED TO BUILD LIBFOSSIL
FOSSIL_CFLAGS =	${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99

# On SOME Linux (e.g., Ubuntu 18.04.6), we have to include wchar curses from
# I/.../ncursesw, but linking to -lncursesw (w/ no special -L path) works fine.
# FLAGS NEEDED TO BUILD FNC
FNC_CFLAGS =	${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99 \
		-I./lib -I/usr/include/ncursesw -D_XOPEN_SOURCE_EXTENDED \
		-DVERSION=${VERSION}

FNC_LDFLAGS =	${LDFLAGS} -lm -lutil -lz -lpthread -fPIC

# OSX has ncursesw, and needs iconv.
ifeq ($(UNAME),Darwin)
# OSX
FNC_LDFLAGS +=	-lncurses -lpanel -liconv
else
# Linux (tested on Debian), OpenBSD, FreeBSD
FNC_LDFLAGS +=	-lncursesw -lpanelw
endif

all: bin

bin: lib/sqlite3.o lib/libfossil.o src/fnc.o src/fnc

lib/sqlite3.o: lib/sqlite3.c lib/sqlite3.h $(MAKEFILE)
	${CC} ${SQLITE_CFLAGS} -c $< -o $@

lib/libfossil.o: lib/libfossil.c lib/libfossil.h $(MAKEFILE)
	${CC} ${FOSSIL_CFLAGS} -c $< -o $@

src/fnc.o: src/fnc.c $(MAKEFILE)
	${CC} ${FNC_CFLAGS} -c $< -o $@

src/fnc: src/fnc.o lib/libfossil.o lib/sqlite3.o $(MAKEFILE)
	${CC} -o $@ src/fnc.o lib/libfossil.o lib/sqlite3.o ${FNC_LDFLAGS}

install:
	install -s -m 0755 src/fnc ${PREFIX}/bin/fnc
	install -m 0644 src/fnc.1 ${PREFIX}${MANDIR}/man1/fnc.1

uninstall:
	rm -f ${PREFIX}/bin/fnc ${PREFIX}${MANDIR}/man1/fnc.1

clean:
	rm -f lib/*.o src/*.o src/fnc

release: clean
	tar czvf ../fnc-${VERSION}.tgz -C .. fnc-${VERSION}

.PHONY: clean release

Deleted Makefile.in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52




















































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
#!/usr/bin/make # help out emacs
#
# Top-level autosetup-filtered Makefile for libfossil. This particular
# build is for Unix platforms with GNU Make 3.81+.
all:
.NOTPARALLEL: # stop subdir makes and reconfigure from launching
              # multiple times concurrently.
include config.make
ShakeNMake.CISH_SOURCES := $(wildcard *.c)
# Subdir cleanup rules and deps list must come before shakenmake.make is included
# or they must be set up manually afterwards...
clean-.: clean-fnc clean-src
distclean-.: distclean-fnc distclean-src
include shakenmake.make
MAIN_MAKEFILES := $(PACKAGE.MAKEFILE) $(ShakeNMake.MAKEFILE) @AUTODEPS@

SUBDIRS := src fnc
$(eval $(call ShakeNMake.CALL.SUBDIRS,$(SUBDIRS)))
subdir-fnc: subdir-src
all: subdir-src subdir-fnc

DISTCLEAN_FILES += config.make

########################################################################
# Other stuff...

ifeq ($(MAKE_COMPILATION_DB),yes)
all: compile_commands.json
compile_commands.json:
	@$(RM) $@
	sed -e '1s/^/[\'$$'\n''/' -e '$$s/,$$/\'$$'\n'']/' $(compdb_dir)/*.o.json > $@+
	@if test -s $@+; then mv $@+ $@; else $(RM) $@+; fi
endif

DISTCLEAN_FILES += Makefile config.log autosetup/jimsh0 \
	$(wildcard compile_commands/*) compile_commands.json+

# Reconfigure if needed
ifeq ($(findstring clean,$(MAKECMDGOALS)),)
@top_srcdir@/config.make: @AUTODEPS@ @top_srcdir@/config.make.in
	@@AUTOREMAKE@
@top_srcdir@/Makefile: @AUTODEPS@ @top_srcdir@/Makefile.in
	chmod +w $@
	@@AUTOREMAKE@
@top_srcdir@/vars.make: @AUTODEPS@ @top_srcdir@/vars.make.in
	@@AUTOREMAKE@
endif

# Or on demand
reconfig:
	@AUTOREMAKE@

Changes to README.md.

23
24
25
26
27
28
29
30
31
32

33
34

35
36

37
38
39
40

41
42
43
44


45
46
47
48
49
50
51
23
24
25
26
27
28
29



30
31

32
33

34
35
36
37

38




39
40
41
42
43
44
45
46
47







-
-
-
+

-
+

-
+



-
+
-
-
-
-
+
+








# Build

1. clone the repository
  - `fossil clone https://fnc.bsdbox.org`
2. move into the repository checkout
  - `cd fnc`
3. run the configure script
  - `./configure`
4. build fnc
3. build fnc
  - `make`
5. install the `fnc` binary (*requires privileges*)
4. install the `fnc` binary (*requires privileges*)
  - `doas make install`
6. move into an open Fossil checkout, and run it:
5. move into an open Fossil checkout, and run it:
  - `cd ~/museum/repo && fossil open ../repo.fossil && fnc`

This will install the `fnc` executable and man page into `/usr/local/bin` and
`/usr/local/share/man/man1`, respectively. To change the install path, use the
`/usr/local/share/man/man1`, respectively. Alternatively, cryptographically
`--prefix` option to `configure`; for example, replacing step 3 with
`./configure --prefix=$HOME` will install the executable and man page into
`~/bin` and `~/share/man`, respectively. Alternatively, cryptographically signed
binaries for some of the abovementioned platforms are available to [download][3].
signed binaries for some of the abovementioned platforms are available to
[download][3].

# Doc

See `fnc --help` for a quick reference, and the [fnc(1)][4] manual page for more
comprehensive documentation. In-app help can also be accessed with the `?`,
`F1`, or `H` key binding. The following video briefly demonstrates some of the
key bindings in use.

Deleted auto.def.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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






























































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# vim:se syn=tcl:
#
use cc cc-shared cc-lib wh-common

options {
    no-debug=0 => "Disable debug build options."
    loud=0 => "Enables 'loud' build mode."
    profile=0 => "Enables the -pg (profiling) compile/link flag if CC is gcc."
    no-compile-commands=0 =>
      "Disable compile_commands.json support even if detected (possibly incorrectly)."
}


# autosetup interceps 'debug' and 'enable-debug' flags :/
#    prefix:=[get-env HOME /usr/local] -> "Installation prefix."

#cc-check-c11

wh-require-bash
cc-check-sizeof "void *"

if {![cc-check-includes zlib.h] ||
    ![cc-check-function-in-lib compress z]} {
    user-error "Missing functional zlib"
}
cc-check-function-in-lib iconv iconv

########################################################################
# Checks for C99 via (__STDC_VERSION__ >= 199901L). Returns 1 if so, 0
# 0 if not.
proc cc-check-c99 {} {
    msg-checking "Checking for C99 via __STDC_VERSION__... "
    if {[cctest -code {
        #if !defined(__STDC_VERSION__) || __STDC_VERSION__<199901L
        # error "Not C99"
        #endif
    }]} {
        msg-result "got C99"
        return 1
    }
    return 0
}

# The compiler may be able to run in C99 mode without -std=c99, but we
# check for that flag anyway because without it we might inadvertently
# be compiling against a newer C standard for purposes of flags like
# -pedantic
set CC_FLAG_C99 {-std=c99}
if {![cc-check-flags $CC_FLAG_C99]} {
    set CC_FLAG_C99 {}
}
if {![cc-check-c99]} {
    user-error "As of 2021-02-21, libfossil requires C99."
}

define CC_FLAG_C99 $CC_FLAG_C99

# cc-check-functions getcwd fopen
cc-check-functions opendir stat pipe inet_ntop getaddrinfo
#msg-result [cc-check-functions lstat]

if {[cc-check-functions lstat]} {
    # for lstat() on Linux and FreeBSD:
    define _XOPEN_SOURCE 600
    # alternate for lstat() on Linux:
    # define _BSD_SOURCE 1
    # ^^^^ causes warning (-Werror breakage) with glibc >=2.20
    define _DEFAULT_SOURCE 1
    define _POSIX_C_SOURCE 200112L
}

# Find some tools
cc-check-tools ar strip
wh-bin-define install

set extra_objs {}

if {[find-an-executable cygpath] ne "" || $::tcl_platform(os)=="Windows NT"} {
  set cFlags {}
} else {
  set cFlags {-fPIC}
}

if {![wh-check-ncurses]} {
    user-error "Could not find a compatible ncurses/libpanel configuration."
}

if {[opt-bool no-debug]} {
    msg-result "Non-debug build."
    set cFlags "$cFlags -O2"
} else {
    msg-result "Debug build enabled. Use --no-debug to build in non-debug mode."
    set cFlags "$cFlags -g -DDEBUG -O0"
}

wh-check-compile-commands no-compile-commands

define CFLAGS $cFlags
if {[wh-opt-bool-01 -v loud BUILD_QUIETLY]} {
    puts "Enabling quiet build mode. Use --loud to enable loud mode."
}

msg-checking "gprof profiling? "
if {[wh-check-profile-flag profile]} {
  msg-result "gcc detected: building with profiling option."
  # Add CC_PROFILE_FLAG to CFLAGS and LDFLAGS in config.make.in.
} else {
  msg-result "no. Use --profile and gcc to enable."
}

# Each generated Makefile requires an input file with a .in extension:
wh-make-from-dot-in {
    config.make
    Makefile
    src/Makefile
    fnc/Makefile
}

if {0} {
    # Achtung: ordering of the -bare/-str options here is important
    # because of the mixed use of strings and integers for #defines...
    make-config-header include/fossil-scm/autoconfig.h \
        -none {DOXYGEN_*} \
        -bare {HAVE_*  FSL_ENABLE_* _DEFAULT_SOURCE _XOPEN_SOURCE} \
        -str {FSL_* PACKAGE_*}
}

Deleted autosetup/LICENSE.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35



































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Unless explicitly stated, all files which form part of autosetup
are released under the following license:

---------------------------------------------------------------------
autosetup - A build environment "autoconfigurator"

Copyright (c) 2010-2011, WorkWare Systems <http://workware.net.au/>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
   copyright notice, this list of conditions and the following
   disclaimer in the documentation and/or other materials
   provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE WORKWARE SYSTEMS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WORKWARE
SYSTEMS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation
are those of the authors and should not be interpreted as representing
official policies, either expressed or implied, of WorkWare Systems.

Deleted autosetup/README.autosetup.

1
2
3
4
5
6
7
8
9
10
11











-
-
-
-
-
-
-
-
-
-
-
README.autosetup created by autosetup v0.7.0+

This is the autosetup directory for a local install of autosetup.
It contains autosetup, support files and loadable modules.

*.tcl files in this directory are optional modules which
can be loaded with the 'use' directive.

*.auto files in this directory are auto-loaded.

For more information, see http://msteveb.github.io/autosetup/

Deleted autosetup/autosetup.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
671
672
673
674
675
676
677
678
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
737
738
739
740
741
742
743
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
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
817
818
819
820
821
822
823
824
825
826
827
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
860
861
862
863
864
865
866
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
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
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
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
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
1342
1343
1344
1345
1346
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
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
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
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
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
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
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
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
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
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
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
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
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
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
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
2476
2477
2478














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
#!/bin/sh
# Copyright (c) 2006-2011 WorkWare Systems http://www.workware.net.au/
# All rights reserved
# vim:se syntax=tcl:
# \
dir=`dirname "$0"`; exec "`$dir/autosetup-find-tclsh`" "$0" "$@"

# Note that the version has a trailing + on unreleased versions
set autosetup(version) 0.7.0+

# Can be set to 1 to debug early-init problems
set autosetup(debug) [expr {"--debug" in $argv}]

##################################################################
#
# Main flow of control, option handling
#
proc main {argv} {
	global autosetup define

	# There are 3 potential directories involved:
	# 1. The directory containing autosetup (this script)
	# 2. The directory containing auto.def
	# 3. The current directory

	# From this we need to determine:
	# a. The path to this script (and related support files)
	# b. The path to auto.def
	# c. The build directory, where output files are created

	# This is also complicated by the fact that autosetup may
	# have been run via the configure wrapper ([getenv WRAPPER] is set)

	# Here are the rules.
	# a. This script is $::argv0
	#    => dir, prog, exe, libdir
	# b. auto.def is in the directory containing the configure wrapper,
	#    otherwise it is in the current directory.
	#    => srcdir, autodef
	# c. The build directory is the current directory
	#    => builddir, [pwd]

	# 'misc' is needed before we can do anything, so set a temporary libdir
	# in case this is the development version
	set autosetup(libdir) [file dirname $::argv0]/lib
	use misc

	# (a)
	set autosetup(dir) [realdir [file dirname [realpath $::argv0]]]
	set autosetup(prog) [file join $autosetup(dir) [file tail $::argv0]]
	set autosetup(exe) [getenv WRAPPER $autosetup(prog)]
	if {$autosetup(installed)} {
		set autosetup(libdir) $autosetup(dir)
	} else {
		set autosetup(libdir) [file join $autosetup(dir) lib]
	}
	autosetup_add_dep $autosetup(prog)

	# (b)
	if {[getenv WRAPPER ""] eq ""} {
		# Invoked directly
		set autosetup(srcdir) [pwd]
	} else {
		# Invoked via the configure wrapper
		set autosetup(srcdir) [file-normalize [file dirname $autosetup(exe)]]
	}
	set autosetup(autodef) [relative-path $autosetup(srcdir)/auto.def]

	# (c)
	set autosetup(builddir) [pwd]

	set autosetup(argv) $argv
	set autosetup(cmdline) {}
	# options is a list of known options
	set autosetup(options) {}
	# optset is a dictionary of option values set by the user based on getopt
	set autosetup(optset) {}
	# optdefault is a dictionary of default values
	set autosetup(optdefault) {}
	# options-defaults is a dictionary of overrides for default values for options
	set autosetup(options-defaults) {}
	set autosetup(optionhelp) {}
	set autosetup(showhelp) 0

	use util

	# Parse options
	use getopt

	# At the is point we don't know what is a valid option
	# We simply parse anything that looks like an option
	set autosetup(getopt) [getopt argv]

	#"=Core Options:"
	options-add {
		help:=all       => "display help and options. Optional: module name, such as --help=system"
		licence license => "display the autosetup license"
		version         => "display the version of autosetup"
		ref:=text manual:=text
		reference:=text => "display the autosetup command reference. 'text', 'wiki', 'asciidoc' or 'markdown'"
		debug           => "display debugging output as autosetup runs"
		install:=.      => "install autosetup to the current or given directory"
	}
	if {$autosetup(installed)} {
		# hidden options so we can produce a nice error
		options-add {
			sysinstall:path
		}
	} else {
		options-add {
			sysinstall:path  => "install standalone autosetup to the given directory (e.g.: /usr/local)"
		}
	}
	options-add {
		force init:=help   => "create initial auto.def, etc.  Use --init=help for known types"
		# Undocumented options
		option-checking=1
		nopager
		quiet
		timing
		conf:
	}

	if {[opt-bool version]} {
		puts $autosetup(version)
		exit 0
	}

	# autosetup --conf=alternate-auto.def
	if {[opt-str conf o]} {
		set autosetup(autodef) $o
	}

	# Debugging output (set this early)
	incr autosetup(debug) [opt-bool debug]
	incr autosetup(force) [opt-bool force]
	incr autosetup(msg-quiet) [opt-bool quiet]
	incr autosetup(msg-timing) [opt-bool timing]

	# If the local module exists, source it now to allow for
	# project-local customisations
	if {[file exists $autosetup(libdir)/local.tcl]} {
		use local
	}

	# Now any auto-load modules
	autosetup_load_auto_modules

	if {[opt-str help o]} {
		incr autosetup(showhelp)
		use help
		autosetup_help $o
	}

	if {[opt-bool licence license]} {
		use help
		autosetup_show_license
		exit 0
	}

	if {[opt-str {manual ref reference} o]} {
		use help
		autosetup_reference $o
	}

	# Allow combining --install and --init
	set earlyexit 0
	if {[opt-str install o]} {
		use install
		autosetup_install $o
		incr earlyexit
	}

	if {[opt-str init o]} {
		use init
		autosetup_init $o
		incr earlyexit
	}

	if {$earlyexit} {
		exit 0
	}
	if {[opt-str sysinstall o]} {
		use install
		autosetup_install $o 1
		exit 0
	}

	if {![file exists $autosetup(autodef)]} {
		# Check for invalid option first
		options {}
		user-error "No auto.def found in \"$autosetup(srcdir)\" (use [file tail $::autosetup(exe)] --init to create one)"
	}

	# Parse extra arguments into autosetup(cmdline)
	foreach arg $argv {
		if {[regexp {([^=]*)=(.*)} $arg -> n v]} {
			dict set autosetup(cmdline) $n $v
			define $n $v
		} else {
			user-error "Unexpected parameter: $arg"
		}
	}

	autosetup_add_dep $autosetup(autodef)

	# Add $argv to CONFIGURE_OPTS, but ignore duplicates and quote if needed
	set configure_opts {}
	foreach arg $autosetup(argv) {
		set quoted [quote-if-needed $arg]
		# O(n^2), but n will be small
		if {$quoted ni $configure_opts} {
			lappend configure_opts $quoted
		}
	}
	define CONFIGURE_OPTS [join $configure_opts]
	define AUTOREMAKE [quote-if-needed $autosetup(exe)]
	define-append AUTOREMAKE [get-define CONFIGURE_OPTS]


	# Log how we were invoked
	configlog "Invoked as: [getenv WRAPPER $::argv0] [quote-argv $autosetup(argv)]"
	configlog "Tclsh: [info nameofexecutable]"

	# Load auto.def as module "auto.def"
	autosetup_load_module auto.def source $autosetup(autodef)

	# Could warn here if options {} was not specified

	show-notices

	if {$autosetup(debug)} {
		msg-result "Writing all defines to config.log"
		configlog "================ defines ======================"
		foreach n [lsort [array names define]] {
			configlog "define $n $define($n)"
		}
	}

	exit 0
}

# @opt-bool ?-nodefault? option ...
#
# Check each of the named, boolean options and if any have been explicitly enabled
# or disabled by the user, return 1 or 0 accordingly.
#
# If the option was specified more than once, the last value wins.
# e.g. With '--enable-foo --disable-foo', '[opt-bool foo]' will return 0
#
# If no value was specified by the user, returns the default value for the
# first option. If '-nodefault' is given, this behaviour changes and
# -1 is returned instead.
#
proc opt-bool {args} {
	set nodefault 0
	if {[lindex $args 0] eq "-nodefault"} {
		set nodefault 1
		set args [lrange $args 1 end]
	}
	option-check-names {*}$args

	foreach opt $args {
		if {[dict exists $::autosetup(optset) $opt]} {
			return [dict get $::autosetup(optset) $opt]
		}
	}

	if {$nodefault} {
		return -1
	}
	# Default value is the default for the first option
	return [dict get $::autosetup(optdefault) [lindex $args 0]]
}

# @opt-val optionlist ?default=""?
#
# Returns a list containing all the values given for the non-boolean options in '$optionlist'.
# There will be one entry in the list for each option given by the user, including if the
# same option was used multiple times.
#
# If no options were set, '$default' is returned (exactly, not as a list).
#
# Note: For most use cases, 'opt-str' should be preferred.
#
proc opt-val {names {default ""}} {
	option-check-names {*}$names

	foreach opt $names {
		if {[dict exists $::autosetup(optset) $opt]} {
			lappend result {*}[dict get $::autosetup(optset) $opt]
		}
	}
	if {[info exists result]} {
		return $result
	}
	return $default
}

# @opt-str optionlist varname ?default?
#
# Sets '$varname' in the callers scope to the value for one of the given options.
#
# For the list of options given in '$optionlist', if any value is set for any option,
# the option value is taken to be the *last* value of the last option (in the order given).
#
# If no option was given, and a default was specified with 'options-defaults',
# that value is used.
#
# If no 'options-defaults' value was given and '$default' was given, it is used.
#
# If none of the above provided a value, no value is set.
#
# The return value depends on whether '$default' was specified.
# If it was, the option value is returned.
# If it was not, 1 is returns if a value was set, or 0 if not.
#
# Typical usage is as follows:
#
## if {[opt-str {myopt altname} o]} {
##     do something with $o
## }
#
# Or:
## define myname [opt-str {myopt altname} o "/usr/local"]
#
proc opt-str {names varname args} {
	global autosetup

	option-check-names {*}$names
	upvar $varname value

	if {[llength $args]} {
		# A default was given, so always return the string value of the option
		set default [lindex $args 0]
		set retopt 1
	} else {
		# No default, so return 0 or 1 to indicate if a value was found
		set retopt 0
	}

	foreach opt $names {
		if {[dict exists $::autosetup(optset) $opt]} {
			set result [lindex [dict get $::autosetup(optset) $opt] end]
		}
	}

	if {![info exists result]} {
		# No user-specified value. Has options-defaults been set?
		foreach opt $names {
			if {[dict exists $::autosetup(optdefault) $opt]} {
				set result [dict get $autosetup(optdefault) $opt]
			}
		}
	}

	if {[info exists result]} {
		set value $result
		if {$retopt} {
			return $value
		}
		return 1
	}

	if {$retopt} {
		set value $default
		return $value
	}

	return 0
}

proc option-check-names {args} {
	foreach o $args {
		if {$o ni $::autosetup(options)} {
			autosetup-error "Request for undeclared option --$o"
		}
	}
}

# Parse the option definition in $opts and update
# ::autosetup(setoptions) and ::autosetup(optionhelp) appropriately
#
proc options-add {opts} {
	global autosetup

	# First weed out comment lines
	set realopts {}
	foreach line [split $opts \n] {
		if {![string match "#*" [string trimleft $line]]} {
			append realopts $line \n
		}
	}
	set opts $realopts

	for {set i 0} {$i < [llength $opts]} {incr i} {
		set opt [lindex $opts $i]
		if {[string match =* $opt]} {
			# This is a special heading
			lappend autosetup(optionhelp) [list $opt $autosetup(module)]
			continue
		}
		unset -nocomplain defaultvalue equal value

		#puts "i=$i, opt=$opt"
		regexp {^([^:=]*)(:)?(=)?(.*)$} $opt -> name colon equal value
		if {$name in $autosetup(options)} {
			autosetup-error "Option $name already specified"
		}

		#puts "$opt => $name $colon $equal $value"

		# Find the corresponding value in the user options
		# and set the default if necessary
		if {[string match "-*" $opt]} {
			# This is a documentation-only option, like "-C <dir>"
			set opthelp $opt
		} elseif {$colon eq ""} {
			# Boolean option
			lappend autosetup(options) $name

			# Check for override
			if {[dict exists $autosetup(options-defaults) $name]} {
				# A default was specified with options-defaults, so use it
				set value [dict get $autosetup(options-defaults) $name]
			}

			if {$value eq "1"} {
				set opthelp "--disable-$name"
			} else {
				set opthelp "--$name"
			}

			# Set the default
			if {$value eq ""} {
				set value 0
			}
			set defaultvalue $value
			dict set autosetup(optdefault) $name $defaultvalue

			if {[dict exists $autosetup(getopt) $name]} {
				# The option was specified by the user. Look at the last value.
				lassign [lindex [dict get $autosetup(getopt) $name] end] type setvalue
				if {$type eq "str"} {
					# Can we convert the value to a boolean?
					if {$setvalue in {1 enabled yes}} {
						set setvalue 1
					} elseif {$setvalue in {0 disabled no}} {
						set setvalue 0
					} else {
						user-error "Boolean option $name given as --$name=$setvalue"
					}
				}
				dict set autosetup(optset) $name $setvalue
				#puts "Found boolean option --$name=$setvalue"
			}
		} else {
			# String option.
			lappend autosetup(options) $name

			if {$equal ne "="} {
				# Was the option given as "name:value=default"?
				# If so, set $value to the display name and $defaultvalue to the default
				# (This is the preferred way to set a default value for a string option)
				if {[regexp {^([^=]+)=(.*)$} $value -> value defaultvalue]} {
					dict set autosetup(optdefault) $name $defaultvalue
				}
			}

			# Maybe override the default value
			if {[dict exists $autosetup(options-defaults) $name]} {
				# A default was specified with options-defaults, so use it
				set defaultvalue [dict get $autosetup(options-defaults) $name]
				dict set autosetup(optdefault) $name $defaultvalue
			} elseif {![info exists defaultvalue]} {
				# No default value was given by value=default or options-defaults
				# so use the value as the default when the plain option with no
				# value is given (.e.g. just --opt instead of --opt=value)
				set defaultvalue $value
			}

			if {$equal eq "="} {
				# String option with optional value
				set opthelp "--$name?=$value?"
			} else {
				# String option with required value
				set opthelp "--$name=$value"
			}

			# Get the values specified by the user
			if {[dict exists $autosetup(getopt) $name]} {
				set listvalue {}

				foreach pair [dict get $autosetup(getopt) $name] {
					lassign $pair type setvalue
					if {$type eq "bool" && $setvalue} {
						if {$equal ne "="} {
							user-error "Option --$name requires a value"
						}
						# If given as a boolean, use the default value
						set setvalue $defaultvalue
					}
					lappend listvalue $setvalue
				}

				#puts "Found string option --$name=$listvalue"
				dict set autosetup(optset) $name $listvalue
			}
		}

		# Now create the help for this option if appropriate
		if {[lindex $opts $i+1] eq "=>"} {
			set desc [lindex $opts $i+2]
			if {[info exists defaultvalue]} {
				set desc [string map [list @default@ $defaultvalue] $desc]
			}
			# A multi-line description
			lappend autosetup(optionhelp) [list $opthelp $autosetup(module) $desc]
			incr i 2
		}
	}
}

# @module-options optionlist
#
# Deprecated. Simply use 'options' from within a module.
proc module-options {opts} {
	options $opts
}

proc max {a b} {
	expr {$a > $b ? $a : $b}
}

proc options-wrap-desc {text length firstprefix nextprefix initial} {
	set len $initial
	set space $firstprefix
	foreach word [split $text] {
		set word [string trim $word]
		if {$word == ""} {
			continue
		}
		if {$len && [string length $space$word] + $len >= $length} {
			puts ""
			set len 0
			set space $nextprefix
		}
		incr len [string length $space$word]
		puts -nonewline $space$word
		set space " "
	}
	if {$len} {
		puts ""
	}
}

# Display options (from $autosetup(optionhelp)) for modules that match
# glob pattern $what
proc options-show {what} {
	set local 0
	# Determine the max option width
	set max 0
	foreach help $::autosetup(optionhelp) {
		lassign $help opt module desc
		if {![string match $what $module]} {
			continue
		}
		if {[string match =* $opt] || [string match \n* $desc]} {
			continue
		}
		set max [max $max [string length $opt]]
	}
	set indent [string repeat " " [expr {$max+4}]]
	set cols [getenv COLUMNS 80]
	catch {
		lassign [exec stty size] rows cols
	}
	incr cols -1
	# Now output
	foreach help $::autosetup(optionhelp) {
		lassign $help opt module desc
		if {![string match $what $module]} {
			continue
		}
		if {$local == 0 && $module eq "auto.def"} {
			puts "Local Options:"
			incr local
		}
		if {[string match =* $opt]} {
			# Output a special heading line"
			puts [string range $opt 1 end]
			continue
		}
		puts -nonewline "  [format %-${max}s $opt]"
		if {[string match \n* $desc]} {
			# Output a pre-formatted help description as-is
			puts $desc
		} else {
			options-wrap-desc [string trim $desc] $cols "  " $indent [expr {$max+2}]
		}
	}
}

# @options optionspec
#
# Specifies configuration-time options which may be selected by the user
# and checked with 'opt-str' and 'opt-bool'. '$optionspec' contains a series
# of options specifications separated by newlines, as follows:
#
# A boolean option is of the form:
#
## name[=0|1]  => "Description of this boolean option"
#
# The default is 'name=0', meaning that the option is disabled by default.
# If 'name=1' is used to make the option enabled by default, the description should reflect
# that with text like "Disable support for ...".
#
# An argument option (one which takes a parameter) is of one of the following forms:
#
## name:value         => "Description of this option"
## name:value=default => "Description of this option with a default value"
## name:=value        => "Description of this option with an optional value"
#
# If the 'name:value' form is used, the value must be provided with the option (as '--name=myvalue').
# If the 'name:value=default' form is used, the option has the given default value even if not
# specified by the user.
# If the 'name:=value' form is used, the value is optional and the given value is used
# if it is not provided.
#
# The description may contain '@default@', in which case it will be replaced with the default
# value for the option (taking into account defaults specified with 'options-defaults'.
#
# Undocumented options are also supported by omitting the '=> description'.
# These options are not displayed with '--help' and can be useful for internal options or as aliases.
#
# For example, '--disable-lfs' is an alias for '--disable=largefile':
#
## lfs=1 largefile=1 => "Disable large file support"
#
proc options {optlist} {
	global autosetup

	options-add $optlist

	if {$autosetup(showhelp)} {
		# If --help, stop now to show help
		return -code break
	}

	if {$autosetup(module) eq "auto.def"} {
		# Check for invalid options
		if {[opt-bool option-checking]} {
			foreach o [dict keys $::autosetup(getopt)] {
				if {$o ni $::autosetup(options)} {
					user-error "Unknown option --$o"
				}
			}
		}
	}
}

# @options-defaults dictionary
#
# Specifies a dictionary of options and a new default value for each of those options.
# Use before any 'use' statements in 'auto.def' to change the defaults for
# subsequently included modules.
proc options-defaults {dict} {
	foreach {n v} $dict {
		dict set ::autosetup(options-defaults) $n $v
	}
}

proc config_guess {} {
	if {[file-isexec $::autosetup(dir)/autosetup-config.guess]} {
		if {[catch {exec-with-stderr sh $::autosetup(dir)/autosetup-config.guess} alias]} {
			user-error $alias
		}
		return $alias
	} else {
		configlog "No autosetup-config.guess, so using uname"
		string tolower [exec uname -p]-unknown-[exec uname -s][exec uname -r]
	}
}

proc config_sub {alias} {
	if {[file-isexec $::autosetup(dir)/autosetup-config.sub]} {
		if {[catch {exec-with-stderr sh $::autosetup(dir)/autosetup-config.sub $alias} alias]} {
			user-error $alias
		}
	}
	return $alias
}

# @define name ?value=1?
#
# Defines the named variable to the given value.
# These (name, value) pairs represent the results of the configuration check
# and are available to be subsequently checked, modified and substituted.
#
proc define {name {value 1}} {
	set ::define($name) $value
	#dputs "$name <= $value"
}

# @undefine name
#
# Undefine the named variable.
#
proc undefine {name} {
	unset -nocomplain ::define($name)
	#dputs "$name <= <undef>"
}

# @define-append name value ...
#
# Appends the given value(s) to the given "defined" variable.
# If the variable is not defined or empty, it is set to '$value'.
# Otherwise the value is appended, separated by a space.
# Any extra values are similarly appended.
# If any value is already contained in the variable (as a substring) it is omitted.
#
proc define-append {name args} {
	if {[get-define $name ""] ne ""} {
		# Avoid duplicates
		foreach arg $args {
			if {$arg eq ""} {
				continue
			}
			set found 0
			foreach str [split $::define($name) " "] {
				if {$str eq $arg} {
					incr found
				}
			}
			if {!$found} {
				append ::define($name) " " $arg
			}
		}
	} else {
		set ::define($name) [join $args]
	}
	#dputs "$name += [join $args] => $::define($name)"
}

# @get-define name ?default=0?
#
# Returns the current value of the "defined" variable, or '$default'
# if not set.
#
proc get-define {name {default 0}} {
	if {[info exists ::define($name)]} {
		#dputs "$name => $::define($name)"
		return $::define($name)
	}
	#dputs "$name => $default"
	return $default
}

# @is-defined name
#
# Returns 1 if the given variable is defined.
#
proc is-defined {name} {
	info exists ::define($name)
}

# @is-define-set name
#
# Returns 1 if the given variable is defined and is set
# to a value other than "" or 0
#
proc is-define-set {name} {
	if {[get-define $name] in {0 ""}} {
		return 0
	}
	return 1
}

# @all-defines
#
# Returns a dictionary (name, value list) of all defined variables.
#
# This is suitable for use with 'dict', 'array set' or 'foreach'
# and allows for arbitrary processing of the defined variables.
#
proc all-defines {} {
	array get ::define
}


# @get-env name default
#
# If '$name' was specified on the command line, return it.
# Otherwise if '$name' was set in the environment, return it.
# Otherwise return '$default'.
#
proc get-env {name default} {
	if {[dict exists $::autosetup(cmdline) $name]} {
		return [dict get $::autosetup(cmdline) $name]
	}
	getenv $name $default
}

# @env-is-set name
#
# Returns 1 if '$name' was specified on the command line or in the environment.
# Note that an empty environment variable is not considered to be set.
#
proc env-is-set {name} {
	if {[dict exists $::autosetup(cmdline) $name]} {
		return 1
	}
	if {[getenv $name ""] ne ""} {
		return 1
	}
	return 0
}

# @readfile filename ?default=""?
#
# Return the contents of the file, without the trailing newline.
# If the file doesn't exist or can't be read, returns '$default'.
#
proc readfile {filename {default_value ""}} {
	set result $default_value
	catch {
		set f [open $filename]
		set result [read -nonewline $f]
		close $f
	}
	return $result
}

# @writefile filename value
#
# Creates the given file containing '$value'.
# Does not add an extra newline.
#
proc writefile {filename value} {
	set f [open $filename w]
	puts -nonewline $f $value
	close $f
}

proc quote-if-needed {str} {
	if {[string match {*[\" ]*} $str]} {
		return \"[string map [list \" \\" \\ \\\\] $str]\"
	}
	return $str
}

proc quote-argv {argv} {
	set args {}
	foreach arg $argv {
		lappend args [quote-if-needed $arg]
	}
	join $args
}

# @list-non-empty list
#
# Returns a copy of the given list with empty elements removed
proc list-non-empty {list} {
	set result {}
	foreach p $list {
		if {$p ne ""} {
			lappend result $p
		}
	}
	return $result
}

# @find-executable-path name
#
# Searches the path for an executable with the given name.
# Note that the name may include some parameters, e.g. 'cc -mbig-endian',
# in which case the parameters are ignored.
# The full path to the executable if found, or "" if not found.
# Returns 1 if found, or 0 if not.
#
proc find-executable-path {name} {
	# Ignore any parameters
	set name [lindex $name 0]
	# The empty string is never a valid executable
	if {$name ne ""} {
		foreach p [split-path] {
			dputs "Looking for $name in $p"
			set exec [file join $p $name]
			if {[file-isexec $exec]} {
				dputs "Found $name -> $exec"
				return $exec
			}
		}
	}
	return {}
}

# @find-executable name
#
# Searches the path for an executable with the given name.
# Note that the name may include some parameters, e.g. 'cc -mbig-endian',
# in which case the parameters are ignored.
# Returns 1 if found, or 0 if not.
#
proc find-executable {name} {
	if {[find-executable-path $name] eq {}} {
		return 0
	}
	return 1
}

# @find-an-executable ?-required? name ...
#
# Given a list of possible executable names,
# searches for one of these on the path.
#
# Returns the name found, or "" if none found.
# If the first parameter is '-required', an error is generated
# if no executable is found.
#
proc find-an-executable {args} {
	set required 0
	if {[lindex $args 0] eq "-required"} {
		set args [lrange $args 1 end]
		incr required
	}
	foreach name $args {
		if {[find-executable $name]} {
			return $name
		}
	}
	if {$required} {
		if {[llength $args] == 1} {
			user-error "failed to find: [join $args]"
		} else {
			user-error "failed to find one of: [join $args]"
		}
	}
	return ""
}

# @configlog msg
#
# Writes the given message to the configuration log, 'config.log'.
#
proc configlog {msg} {
	if {![info exists ::autosetup(logfh)]} {
		set ::autosetup(logfh) [open config.log w]
	}
	puts $::autosetup(logfh) $msg
}

# @msg-checking msg
#
# Writes the message with no newline to stdout.
#
proc msg-checking {msg} {
	if {$::autosetup(msg-quiet) == 0} {
		maybe-show-timestamp
		puts -nonewline $msg
		set ::autosetup(msg-checking) 1
	}
}

# @msg-result msg
#
# Writes the message to stdout.
#
proc msg-result {msg} {
	if {$::autosetup(msg-quiet) == 0} {
		maybe-show-timestamp
		puts $msg
		set ::autosetup(msg-checking) 0
		show-notices
	}
}

# @msg-quiet command ...
#
# 'msg-quiet' evaluates it's arguments as a command with output
# from 'msg-checking' and 'msg-result' suppressed.
#
# This is useful if a check needs to run a subcheck which isn't
# of interest to the user.
proc msg-quiet {args} {
	incr ::autosetup(msg-quiet)
	set rc [uplevel 1 $args]
	incr ::autosetup(msg-quiet) -1
	return $rc
}

# Will be overridden by 'use misc'
proc error-stacktrace {msg} {
	return $msg
}

proc error-location {msg} {
	return $msg
}

##################################################################
#
# Debugging output
#
proc dputs {msg} {
	if {$::autosetup(debug)} {
		puts $msg
	}
}

##################################################################
#
# User and system warnings and errors
#
# Usage errors such as wrong command line options

# @user-error msg
#
# Indicate incorrect usage to the user, including if required components
# or features are not found.
# 'autosetup' exits with a non-zero return code.
#
proc user-error {msg} {
	show-notices
	puts stderr "Error: $msg"
	puts stderr "Try: '[file tail $::autosetup(exe)] --help' for options"
	exit 1
}

# @user-notice msg
#
# Output the given message to stderr.
#
proc user-notice {msg} {
	lappend ::autosetup(notices) $msg
}

# Incorrect usage in the auto.def file. Identify the location.
proc autosetup-error {msg} {
	autosetup-full-error [error-location $msg]
}

# Like autosetup-error, except $msg is the full error message.
proc autosetup-full-error {msg} {
	show-notices
	puts stderr $msg
	exit 1
}

proc show-notices {} {
	if {$::autosetup(msg-checking)} {
		puts ""
		set ::autosetup(msg-checking) 0
	}
	flush stdout
	if {[info exists ::autosetup(notices)]} {
		puts stderr [join $::autosetup(notices) \n]
		unset ::autosetup(notices)
	}
}

proc maybe-show-timestamp {} {
	if {$::autosetup(msg-timing) && $::autosetup(msg-checking) == 0} {
		puts -nonewline [format {[%6.2f] } [expr {([clock millis] - $::autosetup(start)) % 10000 / 1000.0}]]
	}
}

# @autosetup-require-version required
#
# Checks the current version of 'autosetup' against '$required'.
# A fatal error is generated if the current version is less than that required.
#
proc autosetup-require-version {required} {
	if {[compare-versions $::autosetup(version) $required] < 0} {
		user-error "autosetup version $required is required, but this is $::autosetup(version)"
	}
}

proc autosetup_version {} {
	return "autosetup v$::autosetup(version)"
}

##################################################################
#
# Directory/path handling
#

proc realdir {dir} {
	set oldpwd [pwd]
	cd $dir
	set pwd [pwd]
	cd $oldpwd
	return $pwd
}

# Follow symlinks until we get to something which is not a symlink
proc realpath {path} {
	while {1} {
		if {[catch {
			set path [file readlink $path]
		}]} {
			# Not a link
			break
		}
	}
	return $path
}

# Convert absolute path, $path into a path relative
# to the given directory (or the current dir, if not given).
#
proc relative-path {path {pwd {}}} {
	set diff 0
	set same 0
	set newf {}
	set prefix {}
	set path [file-normalize $path]
	if {$pwd eq ""} {
		set pwd [pwd]
	} else {
		set pwd [file-normalize $pwd]
	}

	if {$path eq $pwd} {
		return .
	}

	# Try to make the filename relative to the current dir
	foreach p [split $pwd /] f [split $path /] {
		if {$p ne $f} {
			incr diff
		} elseif {!$diff} {
			incr same
		}
		if {$diff} {
			if {$p ne ""} {
				# Add .. for sibling or parent dir
				lappend prefix ..
			}
			if {$f ne ""} {
				lappend newf $f
			}
		}
	}
	if {$same == 1 || [llength $prefix] > 3} {
		return $path
	}

	file join [join $prefix /] [join $newf /]
}

# Add filename as a dependency to rerun autosetup
# The name will be normalised (converted to a full path)
#
proc autosetup_add_dep {filename} {
	lappend ::autosetup(deps) [file-normalize $filename]
}

##################################################################
#
# Library module support
#

# @use module ...
#
# Load the given library modules.
# e.g. 'use cc cc-shared'
#
# Note that module 'X' is implemented in either 'autosetup/X.tcl'
# or 'autosetup/X/init.tcl'
#
# The latter form is useful for a complex module which requires additional
# support file. In this form, '$::usedir' is set to the module directory
# when it is loaded.
#
proc use {args} {
	global autosetup libmodule modsource

	set dirs [list $autosetup(libdir)]
	if {[info exists autosetup(srcdir)]} {
		lappend dirs $autosetup(srcdir)/autosetup
	}
	foreach m $args {
		if {[info exists libmodule($m)]} {
			continue
		}
		set libmodule($m) 1

		if {[info exists modsource(${m}.tcl)]} {
			autosetup_load_module $m eval $modsource(${m}.tcl)
		} else {
			set locs [list ${m}.tcl ${m}/init.tcl]
			set found 0
			foreach dir $dirs {
				foreach loc $locs {
					set source $dir/$loc
					if {[file exists $source]} {
						incr found
						break
					}
				}
				if {$found} {
					break
				}
			}
			if {$found} {
				# For the convenience of the "use" source, point to the directory
				# it is being loaded from
				set ::usedir [file dirname $source]
				autosetup_load_module $m source $source
				autosetup_add_dep $source
			} else {
				autosetup-error "use: No such module: $m"
			}
		}
	}
}

proc autosetup_load_auto_modules {} {
	global autosetup modsource
	# First load any embedded auto modules
	foreach mod [array names modsource *.auto] {
		autosetup_load_module $mod eval $modsource($mod)
	}
	# Now any external auto modules
	foreach file [glob -nocomplain $autosetup(libdir)/*.auto $autosetup(libdir)/*/*.auto] {
		autosetup_load_module [file tail $file] source $file
	}
}

# Load module source in the global scope by executing the given command
proc autosetup_load_module {module args} {
	global autosetup
	set prev $autosetup(module)
	set autosetup(module) $module

	if {[catch [list uplevel #0 $args] msg opts] ni {0 2 3}} {
		autosetup-full-error [error-dump $msg $opts $::autosetup(debug)]
	}
	set autosetup(module) $prev
}

# Initial settings
set autosetup(exe) $::argv0
set autosetup(istcl) 1
set autosetup(start) [clock millis]
set autosetup(installed) 0
set autosetup(sysinstall) 0
set autosetup(msg-checking) 0
set autosetup(msg-quiet) 0
set autosetup(inittypes) {}
set autosetup(module) autosetup

# Embedded modules are inserted below here
set autosetup(installed) 1
set autosetup(sysinstall) 0
# ----- @module asciidoc-formatting.tcl -----

set modsource(asciidoc-formatting.tcl) {
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Module which provides text formatting
# asciidoc format

use formatting

proc para {text} {
    regsub -all "\[ \t\n\]+" [string trim $text] " "
}
proc title {text} {
    underline [para $text] =
    nl
}
proc p {text} {
    puts [para $text]
    nl
}
proc code {text} {
    foreach line [parse_code_block $text] {
        puts "    $line"
    }
    nl
}
proc codelines {lines} {
    foreach line $lines {
        puts "    $line"
    }
    nl
}
proc nl {} {
    puts ""
}
proc underline {text char} {
    regexp "^(\[ \t\]*)(.*)" $text -> indent words
    puts $text
    puts $indent[string repeat $char [string length $words]]
}
proc section {text} {
    underline "[para $text]" -
    nl
}
proc subsection {text} {
    underline "$text" ~
    nl
}
proc bullet {text} {
    puts "* [para $text]"
}
proc indent {text} {
    puts " :: "
    puts [para $text]
}
proc defn {first args} {
    set sep ""
    if {$first ne ""} {
        puts "${first}::"
    } else {
        puts " :: "
    }
    set defn [string trim [join $args \n]]
    regsub -all "\n\n" $defn "\n ::\n" defn
    puts $defn
}
}

# ----- @module formatting.tcl -----

set modsource(formatting.tcl) {
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Module which provides common text formatting

# This is designed for documentation which looks like:
# code {...}
# or
# code {
#    ...
#    ...
# }
# In the second case, we need to work out the indenting
# and strip it from all lines but preserve the remaining indenting.
# Note that all lines need to be indented with the same initial
# spaces/tabs.
#
# Returns a list of lines with the indenting removed.
#
proc parse_code_block {text} {
    # If the text begins with newline, take the following text,
    # otherwise just return the original
    if {![regexp "^\n(.*)" $text -> text]} {
        return [list [string trim $text]]
    }

    # And trip spaces off the end
    set text [string trimright $text]

    set min 100
    # Examine each line to determine the minimum indent
    foreach line [split $text \n] {
        if {$line eq ""} {
            # Ignore empty lines for the indent calculation
            continue
        }
        regexp "^(\[ \t\]*)" $line -> indent
        set len [string length $indent]
        if {$len < $min} {
            set min $len
        }
    }

    # Now make a list of lines with this indent removed
    set lines {}
    foreach line [split $text \n] {
        lappend lines [string range $line $min end]
    }

    # Return the result
    return $lines
}
}

# ----- @module getopt.tcl -----

set modsource(getopt.tcl) {
# Copyright (c) 2006 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Simple getopt module

# Parse everything out of the argv list which looks like an option
# Everything which doesn't look like an option, or is after --, is left unchanged
# Understands --enable-xxx as a synonym for --xxx to enable the boolean option xxx.
# Understands --disable-xxx to disable the boolean option xxx.
#
# The returned value is a dictionary keyed by option name
# Each value is a list of {type value} ... where type is "bool" or "str".
# The value for a boolean option is 0 or 1. The value of a string option is the value given.
proc getopt {argvname} {
	upvar $argvname argv
	set nargv {}

	set opts {}

	for {set i 0} {$i < [llength $argv]} {incr i} {
		set arg [lindex $argv $i]

		#dputs arg=$arg

		if {$arg eq "--"} {
			# End of options
			incr i
			lappend nargv {*}[lrange $argv $i end]
			break
		}

		if {[regexp {^--([^=][^=]+)=(.*)$} $arg -> name value]} {
			# --name=value
			dict lappend opts $name [list str $value]
		} elseif {[regexp {^--(enable-|disable-)?([^=]*)$} $arg -> prefix name]} {
			if {$prefix in {enable- ""}} {
				set value 1
			} else {
				set value 0
			}
			dict lappend opts $name [list bool $value]
		} else {
			lappend nargv $arg
		}
	}

	#puts "getopt: argv=[join $argv] => [join $nargv]"
	#array set getopt $opts
	#parray getopt

	set argv $nargv

	return $opts
}
}

# ----- @module help.tcl -----

set modsource(help.tcl) {
# Copyright (c) 2010 WorkWare Systems http://workware.net.au/
# All rights reserved

# Module which provides usage, help and the command reference

proc autosetup_help {what} {
    use_pager

    puts "Usage: [file tail $::autosetup(exe)] \[options\] \[settings\]\n"
    puts "This is [autosetup_version], a build environment \"autoconfigurator\""
    puts "See the documentation online at http://msteveb.github.io/autosetup/\n"

    if {$what in {all local}} {
        # Need to load auto.def now
        if {[file exists $::autosetup(autodef)]} {
            # Load auto.def as module "auto.def"
            autosetup_load_module auto.def source $::autosetup(autodef)
        }
        if {$what eq "all"} {
            set what *
        } else {
            set what auto.def
        }
    } else {
        use $what
        puts "Options for module $what:"
    }
    options-show $what
    exit 0
}

proc autosetup_show_license {} {
    global modsource autosetup
    use_pager

    if {[info exists modsource(LICENSE)]} {
        puts $modsource(LICENSE)
        return
    }
    foreach dir [list $autosetup(libdir) $autosetup(srcdir)] {
        set path [file join $dir LICENSE]
        if {[file exists $path]} {
            puts [readfile $path]
            return
        }
    }
    puts "LICENSE not found"
}

# If not already paged and stdout is a tty, pipe the output through the pager
# This is done by reinvoking autosetup with --nopager added
proc use_pager {} {
    if {![opt-bool nopager] && [getenv PAGER ""] ne "" && [isatty? stdin] && [isatty? stdout]} {
        if {[catch {
            exec [info nameofexecutable] $::argv0 --nopager {*}$::argv |& {*}[getenv PAGER] >@stdout <@stdin 2>@stderr
        } msg opts] == 1} {
            if {[dict get $opts -errorcode] eq "NONE"} {
                # an internal/exec error
                puts stderr $msg
                exit 1
            }
        }
        exit 0
    }
}

# Outputs the autosetup references in one of several formats
proc autosetup_reference {{type text}} {

    use_pager

    switch -glob -- $type {
        wiki {use wiki-formatting}
        ascii* {use asciidoc-formatting}
        md - markdown {use markdown-formatting}
        default {use text-formatting}
    }

    title "[autosetup_version] -- Command Reference"

    section {Introduction}

    p {
        See http://msteveb.github.com/autosetup/ for the online documentation for 'autosetup'
    }

    p {
        'autosetup' provides a number of built-in commands which
        are documented below. These may be used from 'auto.def' to test
        for features, define variables, create files from templates and
        other similar actions.
    }

    automf_command_reference

    exit 0
}

proc autosetup_output_block {type lines} {
    if {[llength $lines]} {
        switch $type {
            section {
                section $lines
            }
            subsection {
                subsection $lines
            }
            code {
                codelines $lines
            }
            p {
                p [join $lines]
            }
            list {
                foreach line $lines {
                    bullet $line
                }
                nl
            }
        }
    }
}

# Generate a command reference from inline documentation
proc automf_command_reference {} {
    lappend files $::autosetup(prog)
    lappend files {*}[lsort [glob -nocomplain $::autosetup(libdir)/*.tcl]]

    # We want to process all non-module files before module files
    # and then modules in alphabetical order.
    # So examine all files and extract docs into doc($modulename) and doc(_core_)
    #
    # Each entry is a list of {type data} where $type is one of: section, subsection, code, list, p
    # and $data is a string for section, subsection or a list of text lines for other types.

    # XXX: Should commands be in alphabetical order too? Currently they are in file order.

    set doc(_core_) {}
    lappend doc(_core_) [list section "Core Commands"]

    foreach file $files {
        set modulename [file rootname [file tail $file]]
        set current _core_
        set f [open $file]
        while {![eof $f]} {
            set line [gets $f]

            # Find embedded module names
            if {[regexp {^#.*@module ([^ ]*)} $line -> modulename]} {
                continue
            }

            # Find lines starting with "# @*" and continuing through the remaining comment lines
            if {![regexp {^# @(.*)} $line -> cmd]} {
                continue
            }

            # Synopsis or command?
            if {$cmd eq "synopsis:"} {
                set current $modulename
                lappend doc($current) [list section "Module: $modulename"]
            } else {
                lappend doc($current) [list subsection $cmd]
            }

            set lines {}
            set type p

            # Now the description
            while {![eof $f]} {
                set line [gets $f]

                if {![regexp {^#(#)? ?(.*)} $line -> hash cmd]} {
                    break
                }
                if {$hash eq "#"} {
                    set t code
                } elseif {[regexp {^- (.*)} $cmd -> cmd]} {
                    set t list
                } else {
                    set t p
                }

                #puts "hash=$hash, oldhash=$oldhash, lines=[llength $lines], cmd=$cmd"

                if {$t ne $type || $cmd eq ""} {
                    # Finish the current block
                    lappend doc($current) [list $type $lines]
                    set lines {}
                    set type $t
                }
                if {$cmd ne ""} {
                    lappend lines $cmd
                }
            }

            lappend doc($current) [list $type $lines]
        }
        close $f
    }

    # Now format and output the results

    # _core_ will sort first
    foreach module [lsort [array names doc]] {
        foreach item $doc($module) {
            autosetup_output_block {*}$item
        }
    }
}
}

# ----- @module init.tcl -----

set modsource(init.tcl) {
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Module to help create auto.def and configure

proc autosetup_init {type} {
	set help 0
	if {$type in {? help}} {
		incr help
	} elseif {![dict exists $::autosetup(inittypes) $type]} {
		puts "Unknown type, --init=$type"
		incr help
	}
	if {$help} {
		puts "Use one of the following types (e.g. --init=make)\n"
		foreach type [lsort [dict keys $::autosetup(inittypes)]] {
			lassign [dict get $::autosetup(inittypes) $type] desc
			# XXX: Use the options-show code to wrap the description
			puts [format "%-10s %s" $type $desc]
		}
		return
	}
	lassign [dict get $::autosetup(inittypes) $type] desc script

	puts "Initialising $type: $desc\n"

	# All initialisations happens in the top level srcdir
	cd $::autosetup(srcdir)

	uplevel #0 $script
}

proc autosetup_add_init_type {type desc script} {
	dict set ::autosetup(inittypes) $type [list $desc $script]
}

# This is for in creating build-system init scripts
#
# If the file doesn't exist, create it containing $contents
# If the file does exist, only overwrite if --force is specified.
#
proc autosetup_check_create {filename contents} {
	if {[file exists $filename]} {
		if {!$::autosetup(force)} {
			puts "I see $filename already exists."
			return
		} else {
			puts "I will overwrite the existing $filename because you used --force."
		}
	} else {
		puts "I don't see $filename, so I will create it."
	}
	writefile $filename $contents
}
}

# ----- @module install.tcl -----

set modsource(install.tcl) {
# Copyright (c) 2006-2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Module which can install autosetup

# autosetup(installed)=1 means that autosetup is not running from source
# autosetup(sysinstall)=1 means that autosetup is running from a sysinstall version
# shared=1 means that we are trying to do a sysinstall. This is only possible from the development source.

proc autosetup_install {dir {shared 0}} {
	global autosetup
	if {$shared} {
		if {$autosetup(installed) || $autosetup(sysinstall)} {
			user-error "Can only --sysinstall from development sources"
		}
	} elseif {$autosetup(installed) && !$autosetup(sysinstall)} {
		user-error "Can't --install from project install"
	}

	if {$autosetup(sysinstall)} {
		# This is the sysinstall version, so install just uses references
		cd $dir

		puts "[autosetup_version] creating configure to use system-installed autosetup"
		autosetup_create_configure 1
		puts "Creating autosetup/README.autosetup"
		file mkdir autosetup
		autosetup_install_readme autosetup/README.autosetup 1
		return
	}

	if {[catch {
		if {$shared} {
			set target $dir/bin/autosetup
			set installedas $target
		} else {
			if {$dir eq "."} {
				set installedas autosetup
			} else {
				set installedas $dir/autosetup
			}
			cd $dir
			file mkdir autosetup
			set target autosetup/autosetup
		}
		set targetdir [file dirname $target]
		file mkdir $targetdir

		set f [open $target w]

		set publicmodules {}

		# First the main script, but only up until "CUT HERE"
		set in [open $autosetup(dir)/autosetup]
		while {[gets $in buf] >= 0} {
			if {$buf ne "##-- CUT HERE --##"} {
				puts $f $buf
				continue
			}

			# Insert the static modules here
			# i.e. those which don't contain @synopsis:
			# All modules are inserted if $shared is set
			puts $f "set autosetup(installed) 1"
			puts $f "set autosetup(sysinstall) $shared"
			foreach file [lsort [glob $autosetup(libdir)/*.{tcl,auto}]] {
				set modname [file tail $file]
				set ext [file ext $modname]
				set buf [readfile $file]
				if {!$shared} {
					if {$ext eq ".auto" || [string match "*\n# @synopsis:*" $buf]} {
						lappend publicmodules $file
						continue
					}
				}
				dputs "install: importing lib/[file tail $file]"
				puts $f "# ----- @module $modname -----"
				puts $f "\nset modsource($modname) \{"
				puts $f $buf
				puts $f "\}\n"
			}
			if {$shared} {
				foreach {srcname destname} [list $autosetup(libdir)/README.autosetup-lib README.autosetup \
						$autosetup(srcdir)/LICENSE LICENSE] {
					dputs "install: importing $srcname as $destname"
					puts $f "\nset modsource($destname) \\\n[list [readfile $srcname]\n]\n"
				}
			}
		}
		close $in
		close $f
		catch {exec chmod 755 $target}

		set installfiles {autosetup-config.guess autosetup-config.sub autosetup-test-tclsh}
		set removefiles {}

		if {!$shared} {
			autosetup_install_readme $targetdir/README.autosetup 0

			# Install public modules
			foreach file $publicmodules {
				set tail [file tail $file]
				autosetup_install_file $file $targetdir/$tail
			}
			lappend installfiles jimsh0.c autosetup-find-tclsh LICENSE
			lappend removefiles config.guess config.sub test-tclsh find-tclsh
		} else {
			lappend installfiles {sys-find-tclsh autosetup-find-tclsh}
		}

		# Install support files
		foreach fileinfo $installfiles {
			if {[llength $fileinfo] == 2} {
				lassign $fileinfo source dest
			} else {
				lassign $fileinfo source
				set dest $source
			}
			autosetup_install_file $autosetup(dir)/$source $targetdir/$dest
		}

		# Remove obsolete files
		foreach file $removefiles {
			if {[file exists $targetdir/$file]} {
				file delete $targetdir/$file
			}
		}
	} error]} {
		user-error "Failed to install autosetup: $error"
	}
	if {$shared} {
		set type "system"
	} else {
		set type "local"
	}
	puts "Installed $type [autosetup_version] to $installedas"

	if {!$shared} {
		# Now create 'configure' if necessary
		autosetup_create_configure 0
	}
}

proc autosetup_create_configure {shared} {
	if {[file exists configure]} {
		if {!$::autosetup(force)} {
			# Could this be an autosetup configure?
			if {![string match "*\nWRAPPER=*" [readfile configure]]} {
				puts "I see configure, but not created by autosetup, so I won't overwrite it."
				puts "Remove it or use --force to overwrite."
				return
			}
		} else {
			puts "I will overwrite the existing configure because you used --force."
		}
	} else {
		puts "I don't see configure, so I will create it."
	}
	if {$shared} {
		writefile configure \
{#!/bin/sh
WRAPPER="$0"; export WRAPPER; "autosetup" "$@"
}
	} else {
		writefile configure \
{#!/bin/sh
dir="`dirname "$0"`/autosetup"
WRAPPER="$0"; export WRAPPER; exec "`"$dir/autosetup-find-tclsh"`" "$dir/autosetup" "$@"
}
	}
	catch {exec chmod 755 configure}
}

# Append the contents of $file to filehandle $f
proc autosetup_install_append {f file} {
	dputs "install: include $file"
	set in [open $file]
	puts $f [read $in]
	close $in
}

proc autosetup_install_file {source target} {
	dputs "install: $source => $target"
	if {![file exists $source]} {
		error "Missing installation file '$source'"
	}
	writefile $target [readfile $source]\n
	# If possible, copy the file mode
	file stat $source stat
	set mode [format %o [expr {$stat(mode) & 0x1ff}]]
	catch {exec chmod $mode $target}
}

proc autosetup_install_readme {target sysinstall} {
	set readme "README.autosetup created by [autosetup_version]\n\n"
	if {$sysinstall} {
		append readme \
{This is the autosetup directory for a system install of autosetup.
Loadable modules can be added here.
}
	} else {
		append readme \
{This is the autosetup directory for a local install of autosetup.
It contains autosetup, support files and loadable modules.
}
}

	append readme {
*.tcl files in this directory are optional modules which
can be loaded with the 'use' directive.

*.auto files in this directory are auto-loaded.

For more information, see http://msteveb.github.io/autosetup/
}
	dputs "install: autosetup/README.autosetup"
	writefile $target $readme
}
}

# ----- @module markdown-formatting.tcl -----

set modsource(markdown-formatting.tcl) {
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Module which provides text formatting
# markdown format (kramdown syntax)

use formatting

proc para {text} {
    regsub -all "\[ \t\n\]+" [string trim $text] " " text
    regsub -all {([^a-zA-Z])'([^']*)'} $text {\1**`\2`**} text
    regsub -all {^'([^']*)'} $text {**`\1`**} text
    regsub -all {(http[^ \t\n]*)} $text {[\1](\1)} text
    return $text
}
proc title {text} {
    underline [para $text] =
    nl
}
proc p {text} {
    puts [para $text]
    nl
}
proc codelines {lines} {
    puts "~~~~~~~~~~~~"
    foreach line $lines {
        puts $line
    }
    puts "~~~~~~~~~~~~"
    nl
}
proc code {text} {
    puts "~~~~~~~~~~~~"
    foreach line [parse_code_block $text] {
        puts $line
    }
    puts "~~~~~~~~~~~~"
    nl
}
proc nl {} {
    puts ""
}
proc underline {text char} {
    regexp "^(\[ \t\]*)(.*)" $text -> indent words
    puts $text
    puts $indent[string repeat $char [string length $words]]
}
proc section {text} {
    underline "[para $text]" -
    nl
}
proc subsection {text} {
    puts "### `$text`"
    nl
}
proc bullet {text} {
    puts "* [para $text]"
}
proc defn {first args} {
    puts "^"
    set defn [string trim [join $args \n]]
    if {$first ne ""} {
        puts "**${first}**"
        puts -nonewline ": "
        regsub -all "\n\n" $defn "\n: " defn
    }
    puts "$defn"
}
}

# ----- @module misc.tcl -----

set modsource(misc.tcl) {
# Copyright (c) 2007-2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Module containing misc procs useful to modules
# Largely for platform compatibility

set autosetup(istcl) [info exists ::tcl_library]
set autosetup(iswin) [string equal windows $tcl_platform(platform)]

if {$autosetup(iswin)} {
	# mingw/windows separates $PATH with semicolons
	# and doesn't have an executable bit
	proc split-path {} {
		split [getenv PATH .] {;}
	}
	proc file-isexec {exec} {
		# Basic test for windows. We ignore .bat
		if {[file isfile $exec] || [file isfile $exec.exe]} {
			return 1
		}
		return 0
	}
} else {
	# unix separates $PATH with colons and has and executable bit
	proc split-path {} {
		split [getenv PATH .] :
	}
	proc file-isexec {exec} {
		file executable $exec
	}
}

# Assume that exec can return stdout and stderr
proc exec-with-stderr {args} {
	exec {*}$args 2>@1
}

if {$autosetup(istcl)} {
	# Tcl doesn't have the env command
	proc getenv {name args} {
		if {[info exists ::env($name)]} {
			return $::env($name)
		}
		if {[llength $args]} {
			return [lindex $args 0]
		}
		return -code error "environment variable \"$name\" does not exist"
	}
	proc isatty? {channel} {
		dict exists [fconfigure $channel] -xchar
	}
} else {
	if {$autosetup(iswin)} {
		# On Windows, backslash convert all environment variables
		# (Assume that Tcl does this for us)
		proc getenv {name args} {
			string map {\\ /} [env $name {*}$args]
		}
	} else {
		# Jim on unix is simple
		alias getenv env
	}
	proc isatty? {channel} {
		set tty 0
		catch {
			# isatty is a recent addition to Jim Tcl
			set tty [$channel isatty]
		}
		return $tty
	}
}

# In case 'file normalize' doesn't exist
#
proc file-normalize {path} {
	if {[catch {file normalize $path} result]} {
		if {$path eq ""} {
			return ""
		}
		set oldpwd [pwd]
		if {[file isdir $path]} {
			cd $path
			set result [pwd]
		} else {
			cd [file dirname $path]
			set result [file join [pwd] [file tail $path]]
		}
		cd $oldpwd
	}
	return $result
}

# If everything is working properly, the only errors which occur
# should be generated in user code (e.g. auto.def).
# By default, we only want to show the error location in user code.
# We use [info frame] to achieve this, but it works differently on Tcl and Jim.
#
# This is designed to be called for incorrect usage in auto.def, via autosetup-error
#
proc error-location {msg} {
	if {$::autosetup(debug)} {
		return -code error $msg
	}
	# Search back through the stack trace for the first error in a .def file
	for {set i 1} {$i < [info level]} {incr i} {
		if {$::autosetup(istcl)} {
			array set info [info frame -$i]
		} else {
			lassign [info frame -$i] info(caller) info(file) info(line)
		}
		if {[string match *.def $info(file)]} {
			return "[relative-path $info(file)]:$info(line): Error: $msg"
		}
		#puts "Skipping $info(file):$info(line)"
	}
	return $msg
}

# If everything is working properly, the only errors which occur
# should be generated in user code (e.g. auto.def).
# By default, we only want to show the error location in user code.
# We use [info frame] to achieve this, but it works differently on Tcl and Jim.
#
# This is designed to be called for incorrect usage in auto.def, via autosetup-error
#
proc error-stacktrace {msg} {
	if {$::autosetup(debug)} {
		return -code error $msg
	}
	# Search back through the stack trace for the first error in a .def file
	for {set i 1} {$i < [info level]} {incr i} {
		if {$::autosetup(istcl)} {
			array set info [info frame -$i]
		} else {
			lassign [info frame -$i] info(caller) info(file) info(line)
		}
		if {[string match *.def $info(file)]} {
			return "[relative-path $info(file)]:$info(line): Error: $msg"
		}
		#puts "Skipping $info(file):$info(line)"
	}
	return $msg
}

# Given the return from [catch {...} msg opts], returns an appropriate
# error message. A nice one for Jim and a less-nice one for Tcl.
# If 'fulltrace' is set, a full stack trace is provided.
# Otherwise a simple message is provided.
#
# This is designed for developer errors, e.g. in module code or auto.def code
#
#
proc error-dump {msg opts fulltrace} {
	if {$::autosetup(istcl)} {
		if {$fulltrace} {
			return "Error: [dict get $opts -errorinfo]"
		} else {
			return "Error: $msg"
		}
	} else {
		lassign $opts(-errorinfo) p f l
		if {$f ne ""} {
			set result "$f:$l: Error: "
		}
		append result "$msg\n"
		if {$fulltrace} {
			append result [stackdump $opts(-errorinfo)]
		}

		# Remove the trailing newline
		string trim $result
	}
}
}

# ----- @module text-formatting.tcl -----

set modsource(text-formatting.tcl) {
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Module which provides text formatting

use formatting

proc wordwrap {text length {firstprefix ""} {nextprefix ""}} {
	set len 0
	set space $firstprefix

	foreach word [split $text] {
		set word [string trim $word]
		if {$word eq ""} {
			continue
		}
		if {[info exists partial]} {
			append partial " " $word
			if {[string first $quote $word] < 0} {
				# Haven't found end of quoted word
				continue
			}
			# Finished quoted word
			set word $partial
			unset partial
			unset quote
		} else {
			set quote [string index $word 0]
			if {$quote in {' *}} {
				if {[string first $quote $word 1] < 0} {
					# Haven't found end of quoted word
					# Not a whole word.
					set first [string index $word 0]
					# Start of quoted word
					set partial $word
					continue
				}
			}
		}

		if {$len && [string length $space$word] + $len >= $length} {
			puts ""
			set len 0
			set space $nextprefix
		}
		incr len [string length $space$word]

		# Use man-page conventions for highlighting 'quoted' and *quoted*
		# single words.
		# Use x^Hx for *bold* and _^Hx for 'underline'.
		#
		# less and more will both understand this.
		# Pipe through 'col -b' to remove them.
		if {[regexp {^'(.*)'(.*)} $word -> quoted after]} {
			set quoted [string map {~ " "} $quoted]
			regsub -all . $quoted "&\b&" quoted
			set word $quoted$after
		} elseif {[regexp {^[*](.*)[*](.*)} $word -> quoted after]} {
			set quoted [string map {~ " "} $quoted]
			regsub -all . $quoted "_\b&" quoted
			set word $quoted$after
		}
		puts -nonewline $space$word
		set space " "
	}
	if {[info exists partial]} {
		# Missing end of quote
		puts -nonewline $space$partial
	}
	if {$len} {
		puts ""
	}
}
proc title {text} {
	underline [string trim $text] =
	nl
}
proc p {text} {
	wordwrap $text 80
	nl
}
proc codelines {lines} {
	foreach line $lines {
		puts "	  $line"
	}
	nl
}
proc nl {} {
	puts ""
}
proc underline {text char} {
	regexp "^(\[ \t\]*)(.*)" $text -> indent words
	puts $text
	puts $indent[string repeat $char [string length $words]]
}
proc section {text} {
	underline "[string trim $text]" -
	nl
}
proc subsection {text} {
	underline "$text" ~
	nl
}
proc bullet {text} {
	wordwrap $text 76 "	 * " "	  "
}
proc indent {text} {
	wordwrap $text 76 "	   " "	  "
}
proc defn {first args} {
	if {$first ne ""} {
		underline "	   $first" ~
	}
	foreach p $args {
		if {$p ne ""} {
			indent $p
		}
	}
}
}

# ----- @module util.tcl -----

set modsource(util.tcl) {
# Copyright (c) 2012 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Module which contains miscellaneous utility functions

# @compare-versions version1 version2
#
# Versions are of the form 'a.b.c' (may be any number of numeric components)
#
# Compares the two versions and returns:
## -1 if v1 < v2
##  0 if v1 == v2
##  1 if v1 > v2
#
# If one version has fewer components than the other, 0 is substituted to the right. e.g.
## 0.2   <  0.3
## 0.2.5 >  0.2
## 1.1   == 1.1.0
#
proc compare-versions {v1 v2} {
	foreach c1 [split $v1 .] c2 [split $v2 .] {
		if {$c1 eq ""} {
			set c1 0
		}
		if {$c2 eq ""} {
			set c2 0
		}
		if {$c1 < $c2} {
			return -1
		}
		if {$c1 > $c2} {
			return 1
		}
	}
	return 0
}

# @suffix suf list
#
# Takes a list and returns a new list with '$suf' appended
# to each element
#
## suffix .c {a b c} => {a.c b.c c.c}
#
proc suffix {suf list} {
	set result {}
	foreach p $list {
		lappend result $p$suf
	}
	return $result
}

# @prefix pre list
#
# Takes a list and returns a new list with '$pre' prepended
# to each element
#
## prefix jim- {a.c b.c} => {jim-a.c jim-b.c}
#
proc prefix {pre list} {
	set result {}
	foreach p $list {
		lappend result $pre$p
	}
	return $result
}

# @lpop list
#
# Removes the last entry from the given list and returns it.
proc lpop {listname} {
	upvar $listname list
	set val [lindex $list end]
	set list [lrange $list 0 end-1]
	return $val
}
}

# ----- @module wiki-formatting.tcl -----

set modsource(wiki-formatting.tcl) {
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Module which provides text formatting
# wiki.tcl.tk format output

use formatting

proc joinlines {text} {
    set lines {}
    foreach l [split [string trim $text] \n] {
        lappend lines [string trim $l]
    }
    join $lines
}
proc p {text} {
    puts [joinlines $text]
    puts ""
}
proc title {text} {
    puts "*** [joinlines $text] ***"
    puts ""
}
proc codelines {lines} {
    puts "======"
    foreach line $lines {
        puts "    $line"
    }
    puts "======"
}
proc code {text} {
    puts "======"
    foreach line [parse_code_block $text] {
        puts "    $line"
    }
    puts "======"
}
proc nl {} {
}
proc section {text} {
    puts "'''$text'''"
    puts ""
}
proc subsection {text} {
    puts "''$text''"
    puts ""
}
proc bullet {text} {
    puts "   * [joinlines $text]"
}
proc indent {text} {
    puts "    :    [joinlines $text]"
}
proc defn {first args} {
    if {$first ne ""} {
        indent '''$first'''
    }

    foreach p $args {
        p $p
    }
}
}


##################################################################
#
# Entry/Exit
#
if {$autosetup(debug)} {
	main $argv
}
if {[catch {main $argv} msg opts] == 1} {
	show-notices
	autosetup-full-error [error-dump $msg $opts $autosetup(debug)]
	if {!$autosetup(debug)} {
		puts stderr "Try: '[file tail $autosetup(exe)] --debug' for a full stack trace"
	}
	exit 1
}

Deleted autosetup/autosetup-config.guess.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
671
672
673
674
675
676
677
678
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
737
738
739
740
741
742
743
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
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
817
818
819
820
821
822
823
824
825
826
827
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
860
861
862
863
864
865
866
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
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
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
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
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
1342
1343
1344
1345
1346
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
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748




















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
#! /bin/sh
# Attempt to guess a canonical system name.
#   Copyright 1992-2021 Free Software Foundation, Inc.

# shellcheck disable=SC2006,SC2268 # see below for rationale

timestamp='2021-06-03'

# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <https://www.gnu.org/licenses/>.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that
# program.  This Exception is an additional permission under section 7
# of the GNU General Public License, version 3 ("GPLv3").
#
# Originally written by Per Bothner; maintained since 2000 by Ben Elliston.
#
# You can get the latest version of this script from:
# https://git.savannah.gnu.org/cgit/config.git/plain/config.guess
#
# Please send patches to <config-patches@gnu.org>.


# The "shellcheck disable" line above the timestamp inhibits complaints
# about features and limitations of the classic Bourne shell that were
# superseded or lifted in POSIX.  However, this script identifies a wide
# variety of pre-POSIX systems that do not have POSIX shells at all, and
# even some reasonably current systems (Solaris 10 as case-in-point) still
# have a pre-POSIX /bin/sh.


me=`echo "$0" | sed -e 's,.*/,,'`

usage="\
Usage: $0 [OPTION]

Output the configuration name of the system \`$me' is run on.

Options:
  -h, --help         print this help, then exit
  -t, --time-stamp   print date of last modification, then exit
  -v, --version      print version number, then exit

Report bugs and patches to <config-patches@gnu.org>."

version="\
GNU config.guess ($timestamp)

Originally written by Per Bothner.
Copyright 1992-2021 Free Software Foundation, Inc.

This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."

help="
Try \`$me --help' for more information."

# Parse command line
while test $# -gt 0 ; do
  case $1 in
    --time-stamp | --time* | -t )
       echo "$timestamp" ; exit ;;
    --version | -v )
       echo "$version" ; exit ;;
    --help | --h* | -h )
       echo "$usage"; exit ;;
    -- )     # Stop option processing
       shift; break ;;
    - )	# Use stdin as input.
       break ;;
    -* )
       echo "$me: invalid option $1$help" >&2
       exit 1 ;;
    * )
       break ;;
  esac
done

if test $# != 0; then
  echo "$me: too many arguments$help" >&2
  exit 1
fi

# Just in case it came from the environment.
GUESS=

# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
# compiler to aid in system detection is discouraged as it requires
# temporary files to be created and, as you can see below, it is a
# headache to deal with in a portable fashion.

# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
# use `HOST_CC' if defined, but it is deprecated.

# Portable tmp directory creation inspired by the Autoconf team.

tmp=
# shellcheck disable=SC2172
trap 'test -z "$tmp" || rm -fr "$tmp"' 0 1 2 13 15

set_cc_for_build() {
    # prevent multiple calls if $tmp is already set
    test "$tmp" && return 0
    : "${TMPDIR=/tmp}"
    # shellcheck disable=SC2039,SC3028
    { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
	{ test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir "$tmp" 2>/dev/null) ; } ||
	{ tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir "$tmp" 2>/dev/null) && echo "Warning: creating insecure temp directory" >&2 ; } ||
	{ echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; }
    dummy=$tmp/dummy
    case ${CC_FOR_BUILD-},${HOST_CC-},${CC-} in
	,,)    echo "int x;" > "$dummy.c"
	       for driver in cc gcc c89 c99 ; do
		   if ($driver -c -o "$dummy.o" "$dummy.c") >/dev/null 2>&1 ; then
		       CC_FOR_BUILD=$driver
		       break
		   fi
	       done
	       if test x"$CC_FOR_BUILD" = x ; then
		   CC_FOR_BUILD=no_compiler_found
	       fi
	       ;;
	,,*)   CC_FOR_BUILD=$CC ;;
	,*,*)  CC_FOR_BUILD=$HOST_CC ;;
    esac
}

# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
# (ghazi@noc.rutgers.edu 1994-08-24)
if test -f /.attbin/uname ; then
	PATH=$PATH:/.attbin ; export PATH
fi

UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown
UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown

case $UNAME_SYSTEM in
Linux|GNU|GNU/*)
	LIBC=unknown

	set_cc_for_build
	cat <<-EOF > "$dummy.c"
	#include <features.h>
	#if defined(__UCLIBC__)
	LIBC=uclibc
	#elif defined(__dietlibc__)
	LIBC=dietlibc
	#elif defined(__GLIBC__)
	LIBC=gnu
	#else
	#include <stdarg.h>
	/* First heuristic to detect musl libc.  */
	#ifdef __DEFINED_va_list
	LIBC=musl
	#endif
	#endif
	EOF
	cc_set_libc=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`
	eval "$cc_set_libc"

	# Second heuristic to detect musl libc.
	if [ "$LIBC" = unknown ] &&
	   command -v ldd >/dev/null &&
	   ldd --version 2>&1 | grep -q ^musl; then
		LIBC=musl
	fi

	# If the system lacks a compiler, then just pick glibc.
	# We could probably try harder.
	if [ "$LIBC" = unknown ]; then
		LIBC=gnu
	fi
	;;
esac

# Note: order is significant - the case branches are not exclusive.

case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in
    *:NetBSD:*:*)
	# NetBSD (nbsd) targets should (where applicable) match one or
	# more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*,
	# *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently
	# switched to ELF, *-*-netbsd* would select the old
	# object file format.  This provides both forward
	# compatibility and a consistent mechanism for selecting the
	# object file format.
	#
	# Note: NetBSD doesn't particularly care about the vendor
	# portion of the name.  We always set it to "unknown".
	UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \
	    /sbin/sysctl -n hw.machine_arch 2>/dev/null || \
	    /usr/sbin/sysctl -n hw.machine_arch 2>/dev/null || \
	    echo unknown)`
	case $UNAME_MACHINE_ARCH in
	    aarch64eb) machine=aarch64_be-unknown ;;
	    armeb) machine=armeb-unknown ;;
	    arm*) machine=arm-unknown ;;
	    sh3el) machine=shl-unknown ;;
	    sh3eb) machine=sh-unknown ;;
	    sh5el) machine=sh5le-unknown ;;
	    earmv*)
		arch=`echo "$UNAME_MACHINE_ARCH" | sed -e 's,^e\(armv[0-9]\).*$,\1,'`
		endian=`echo "$UNAME_MACHINE_ARCH" | sed -ne 's,^.*\(eb\)$,\1,p'`
		machine=${arch}${endian}-unknown
		;;
	    *) machine=$UNAME_MACHINE_ARCH-unknown ;;
	esac
	# The Operating System including object format, if it has switched
	# to ELF recently (or will in the future) and ABI.
	case $UNAME_MACHINE_ARCH in
	    earm*)
		os=netbsdelf
		;;
	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
		set_cc_for_build
		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
			| grep -q __ELF__
		then
		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
		    # Return netbsd for either.  FIX?
		    os=netbsd
		else
		    os=netbsdelf
		fi
		;;
	    *)
		os=netbsd
		;;
	esac
	# Determine ABI tags.
	case $UNAME_MACHINE_ARCH in
	    earm*)
		expr='s/^earmv[0-9]/-eabi/;s/eb$//'
		abi=`echo "$UNAME_MACHINE_ARCH" | sed -e "$expr"`
		;;
	esac
	# The OS release
	# Debian GNU/NetBSD machines have a different userland, and
	# thus, need a distinct triplet. However, they do not need
	# kernel version information, so it can be replaced with a
	# suitable tag, in the style of linux-gnu.
	case $UNAME_VERSION in
	    Debian*)
		release='-gnu'
		;;
	    *)
		release=`echo "$UNAME_RELEASE" | sed -e 's/[-_].*//' | cut -d. -f1,2`
		;;
	esac
	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
	# contains redundant information, the shorter form:
	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
	GUESS=$machine-${os}${release}${abi-}
	;;
    *:Bitrig:*:*)
	UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
	GUESS=$UNAME_MACHINE_ARCH-unknown-bitrig$UNAME_RELEASE
	;;
    *:OpenBSD:*:*)
	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
	GUESS=$UNAME_MACHINE_ARCH-unknown-openbsd$UNAME_RELEASE
	;;
    *:SecBSD:*:*)
	UNAME_MACHINE_ARCH=`arch | sed 's/SecBSD.//'`
	GUESS=$UNAME_MACHINE_ARCH-unknown-secbsd$UNAME_RELEASE
	;;
    *:LibertyBSD:*:*)
	UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'`
	GUESS=$UNAME_MACHINE_ARCH-unknown-libertybsd$UNAME_RELEASE
	;;
    *:MidnightBSD:*:*)
	GUESS=$UNAME_MACHINE-unknown-midnightbsd$UNAME_RELEASE
	;;
    *:ekkoBSD:*:*)
	GUESS=$UNAME_MACHINE-unknown-ekkobsd$UNAME_RELEASE
	;;
    *:SolidBSD:*:*)
	GUESS=$UNAME_MACHINE-unknown-solidbsd$UNAME_RELEASE
	;;
    *:OS108:*:*)
	GUESS=$UNAME_MACHINE-unknown-os108_$UNAME_RELEASE
	;;
    macppc:MirBSD:*:*)
	GUESS=powerpc-unknown-mirbsd$UNAME_RELEASE
	;;
    *:MirBSD:*:*)
	GUESS=$UNAME_MACHINE-unknown-mirbsd$UNAME_RELEASE
	;;
    *:Sortix:*:*)
	GUESS=$UNAME_MACHINE-unknown-sortix
	;;
    *:Twizzler:*:*)
	GUESS=$UNAME_MACHINE-unknown-twizzler
	;;
    *:Redox:*:*)
	GUESS=$UNAME_MACHINE-unknown-redox
	;;
    mips:OSF1:*.*)
	GUESS=mips-dec-osf1
	;;
    alpha:OSF1:*:*)
	# Reset EXIT trap before exiting to avoid spurious non-zero exit code.
	trap '' 0
	case $UNAME_RELEASE in
	*4.0)
		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
		;;
	*5.*)
		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
		;;
	esac
	# According to Compaq, /usr/sbin/psrinfo has been available on
	# OSF/1 and Tru64 systems produced since 1995.  I hope that
	# covers most systems running today.  This code pipes the CPU
	# types through head -n 1, so we only detect the type of CPU 0.
	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
	case $ALPHA_CPU_TYPE in
	    "EV4 (21064)")
		UNAME_MACHINE=alpha ;;
	    "EV4.5 (21064)")
		UNAME_MACHINE=alpha ;;
	    "LCA4 (21066/21068)")
		UNAME_MACHINE=alpha ;;
	    "EV5 (21164)")
		UNAME_MACHINE=alphaev5 ;;
	    "EV5.6 (21164A)")
		UNAME_MACHINE=alphaev56 ;;
	    "EV5.6 (21164PC)")
		UNAME_MACHINE=alphapca56 ;;
	    "EV5.7 (21164PC)")
		UNAME_MACHINE=alphapca57 ;;
	    "EV6 (21264)")
		UNAME_MACHINE=alphaev6 ;;
	    "EV6.7 (21264A)")
		UNAME_MACHINE=alphaev67 ;;
	    "EV6.8CB (21264C)")
		UNAME_MACHINE=alphaev68 ;;
	    "EV6.8AL (21264B)")
		UNAME_MACHINE=alphaev68 ;;
	    "EV6.8CX (21264D)")
		UNAME_MACHINE=alphaev68 ;;
	    "EV6.9A (21264/EV69A)")
		UNAME_MACHINE=alphaev69 ;;
	    "EV7 (21364)")
		UNAME_MACHINE=alphaev7 ;;
	    "EV7.9 (21364A)")
		UNAME_MACHINE=alphaev79 ;;
	esac
	# A Pn.n version is a patched version.
	# A Vn.n version is a released version.
	# A Tn.n version is a released field test version.
	# A Xn.n version is an unreleased experimental baselevel.
	# 1.2 uses "1.2" for uname -r.
	OSF_REL=`echo "$UNAME_RELEASE" | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`
	GUESS=$UNAME_MACHINE-dec-osf$OSF_REL
	;;
    Amiga*:UNIX_System_V:4.0:*)
	GUESS=m68k-unknown-sysv4
	;;
    *:[Aa]miga[Oo][Ss]:*:*)
	GUESS=$UNAME_MACHINE-unknown-amigaos
	;;
    *:[Mm]orph[Oo][Ss]:*:*)
	GUESS=$UNAME_MACHINE-unknown-morphos
	;;
    *:OS/390:*:*)
	GUESS=i370-ibm-openedition
	;;
    *:z/VM:*:*)
	GUESS=s390-ibm-zvmoe
	;;
    *:OS400:*:*)
	GUESS=powerpc-ibm-os400
	;;
    arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
	GUESS=arm-acorn-riscix$UNAME_RELEASE
	;;
    arm*:riscos:*:*|arm*:RISCOS:*:*)
	GUESS=arm-unknown-riscos
	;;
    SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
	GUESS=hppa1.1-hitachi-hiuxmpp
	;;
    Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
	# akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
	case `(/bin/universe) 2>/dev/null` in
	    att) GUESS=pyramid-pyramid-sysv3 ;;
	    *)   GUESS=pyramid-pyramid-bsd   ;;
	esac
	;;
    NILE*:*:*:dcosx)
	GUESS=pyramid-pyramid-svr4
	;;
    DRS?6000:unix:4.0:6*)
	GUESS=sparc-icl-nx6
	;;
    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
	case `/usr/bin/uname -p` in
	    sparc) GUESS=sparc-icl-nx7 ;;
	esac
	;;
    s390x:SunOS:*:*)
	SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`
	GUESS=$UNAME_MACHINE-ibm-solaris2$SUN_REL
	;;
    sun4H:SunOS:5.*:*)
	SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`
	GUESS=sparc-hal-solaris2$SUN_REL
	;;
    sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
	SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`
	GUESS=sparc-sun-solaris2$SUN_REL
	;;
    i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
	GUESS=i386-pc-auroraux$UNAME_RELEASE
	;;
    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
	set_cc_for_build
	SUN_ARCH=i386
	# If there is a compiler, see if it is configured for 64-bit objects.
	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
	# This test works for both compilers.
	if test "$CC_FOR_BUILD" != no_compiler_found; then
	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
		(CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
		grep IS_64BIT_ARCH >/dev/null
	    then
		SUN_ARCH=x86_64
	    fi
	fi
	SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`
	GUESS=$SUN_ARCH-pc-solaris2$SUN_REL
	;;
    sun4*:SunOS:6*:*)
	# According to config.sub, this is the proper way to canonicalize
	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
	# it's likely to be more like Solaris than SunOS4.
	SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`
	GUESS=sparc-sun-solaris3$SUN_REL
	;;
    sun4*:SunOS:*:*)
	case `/usr/bin/arch -k` in
	    Series*|S4*)
		UNAME_RELEASE=`uname -v`
		;;
	esac
	# Japanese Language versions have a version number like `4.1.3-JL'.
	SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/'`
	GUESS=sparc-sun-sunos$SUN_REL
	;;
    sun3*:SunOS:*:*)
	GUESS=m68k-sun-sunos$UNAME_RELEASE
	;;
    sun*:*:4.2BSD:*)
	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
	test "x$UNAME_RELEASE" = x && UNAME_RELEASE=3
	case `/bin/arch` in
	    sun3)
		GUESS=m68k-sun-sunos$UNAME_RELEASE
		;;
	    sun4)
		GUESS=sparc-sun-sunos$UNAME_RELEASE
		;;
	esac
	;;
    aushp:SunOS:*:*)
	GUESS=sparc-auspex-sunos$UNAME_RELEASE
	;;
    # The situation for MiNT is a little confusing.  The machine name
    # can be virtually everything (everything which is not
    # "atarist" or "atariste" at least should have a processor
    # > m68000).  The system name ranges from "MiNT" over "FreeMiNT"
    # to the lowercase version "mint" (or "freemint").  Finally
    # the system name "TOS" denotes a system which is actually not
    # MiNT.  But MiNT is downward compatible to TOS, so this should
    # be no problem.
    atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
	GUESS=m68k-atari-mint$UNAME_RELEASE
	;;
    atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
	GUESS=m68k-atari-mint$UNAME_RELEASE
	;;
    *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
	GUESS=m68k-atari-mint$UNAME_RELEASE
	;;
    milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
	GUESS=m68k-milan-mint$UNAME_RELEASE
	;;
    hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
	GUESS=m68k-hades-mint$UNAME_RELEASE
	;;
    *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
	GUESS=m68k-unknown-mint$UNAME_RELEASE
	;;
    m68k:machten:*:*)
	GUESS=m68k-apple-machten$UNAME_RELEASE
	;;
    powerpc:machten:*:*)
	GUESS=powerpc-apple-machten$UNAME_RELEASE
	;;
    RISC*:Mach:*:*)
	GUESS=mips-dec-mach_bsd4.3
	;;
    RISC*:ULTRIX:*:*)
	GUESS=mips-dec-ultrix$UNAME_RELEASE
	;;
    VAX*:ULTRIX*:*:*)
	GUESS=vax-dec-ultrix$UNAME_RELEASE
	;;
    2020:CLIX:*:* | 2430:CLIX:*:*)
	GUESS=clipper-intergraph-clix$UNAME_RELEASE
	;;
    mips:*:*:UMIPS | mips:*:*:RISCos)
	set_cc_for_build
	sed 's/^	//' << EOF > "$dummy.c"
#ifdef __cplusplus
#include <stdio.h>  /* for printf() prototype */
	int main (int argc, char *argv[]) {
#else
	int main (argc, argv) int argc; char *argv[]; {
#endif
	#if defined (host_mips) && defined (MIPSEB)
	#if defined (SYSTYPE_SYSV)
	  printf ("mips-mips-riscos%ssysv\\n", argv[1]); exit (0);
	#endif
	#if defined (SYSTYPE_SVR4)
	  printf ("mips-mips-riscos%ssvr4\\n", argv[1]); exit (0);
	#endif
	#if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
	  printf ("mips-mips-riscos%sbsd\\n", argv[1]); exit (0);
	#endif
	#endif
	  exit (-1);
	}
EOF
	$CC_FOR_BUILD -o "$dummy" "$dummy.c" &&
	  dummyarg=`echo "$UNAME_RELEASE" | sed -n 's/\([0-9]*\).*/\1/p'` &&
	  SYSTEM_NAME=`"$dummy" "$dummyarg"` &&
	    { echo "$SYSTEM_NAME"; exit; }
	GUESS=mips-mips-riscos$UNAME_RELEASE
	;;
    Motorola:PowerMAX_OS:*:*)
	GUESS=powerpc-motorola-powermax
	;;
    Motorola:*:4.3:PL8-*)
	GUESS=powerpc-harris-powermax
	;;
    Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
	GUESS=powerpc-harris-powermax
	;;
    Night_Hawk:Power_UNIX:*:*)
	GUESS=powerpc-harris-powerunix
	;;
    m88k:CX/UX:7*:*)
	GUESS=m88k-harris-cxux7
	;;
    m88k:*:4*:R4*)
	GUESS=m88k-motorola-sysv4
	;;
    m88k:*:3*:R3*)
	GUESS=m88k-motorola-sysv3
	;;
    AViiON:dgux:*:*)
	# DG/UX returns AViiON for all architectures
	UNAME_PROCESSOR=`/usr/bin/uname -p`
	if test "$UNAME_PROCESSOR" = mc88100 || test "$UNAME_PROCESSOR" = mc88110
	then
	    if test "$TARGET_BINARY_INTERFACE"x = m88kdguxelfx || \
	       test "$TARGET_BINARY_INTERFACE"x = x
	    then
		GUESS=m88k-dg-dgux$UNAME_RELEASE
	    else
		GUESS=m88k-dg-dguxbcs$UNAME_RELEASE
	    fi
	else
	    GUESS=i586-dg-dgux$UNAME_RELEASE
	fi
	;;
    M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
	GUESS=m88k-dolphin-sysv3
	;;
    M88*:*:R3*:*)
	# Delta 88k system running SVR3
	GUESS=m88k-motorola-sysv3
	;;
    XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
	GUESS=m88k-tektronix-sysv3
	;;
    Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
	GUESS=m68k-tektronix-bsd
	;;
    *:IRIX*:*:*)
	IRIX_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/g'`
	GUESS=mips-sgi-irix$IRIX_REL
	;;
    ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
	GUESS=romp-ibm-aix    # uname -m gives an 8 hex-code CPU id
	;;                    # Note that: echo "'`uname -s`'" gives 'AIX '
    i*86:AIX:*:*)
	GUESS=i386-ibm-aix
	;;
    ia64:AIX:*:*)
	if test -x /usr/bin/oslevel ; then
		IBM_REV=`/usr/bin/oslevel`
	else
		IBM_REV=$UNAME_VERSION.$UNAME_RELEASE
	fi
	GUESS=$UNAME_MACHINE-ibm-aix$IBM_REV
	;;
    *:AIX:2:3)
	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
		set_cc_for_build
		sed 's/^		//' << EOF > "$dummy.c"
		#include <sys/systemcfg.h>

		main()
			{
			if (!__power_pc())
				exit(1);
			puts("powerpc-ibm-aix3.2.5");
			exit(0);
			}
EOF
		if $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"`
		then
			GUESS=$SYSTEM_NAME
		else
			GUESS=rs6000-ibm-aix3.2.5
		fi
	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
		GUESS=rs6000-ibm-aix3.2.4
	else
		GUESS=rs6000-ibm-aix3.2
	fi
	;;
    *:AIX:*:[4567])
	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
	if /usr/sbin/lsattr -El "$IBM_CPU_ID" | grep ' POWER' >/dev/null 2>&1; then
		IBM_ARCH=rs6000
	else
		IBM_ARCH=powerpc
	fi
	if test -x /usr/bin/lslpp ; then
		IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | \
			   awk -F: '{ print $3 }' | sed s/[0-9]*$/0/`
	else
		IBM_REV=$UNAME_VERSION.$UNAME_RELEASE
	fi
	GUESS=$IBM_ARCH-ibm-aix$IBM_REV
	;;
    *:AIX:*:*)
	GUESS=rs6000-ibm-aix
	;;
    ibmrt:4.4BSD:*|romp-ibm:4.4BSD:*)
	GUESS=romp-ibm-bsd4.4
	;;
    ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
	GUESS=romp-ibm-bsd$UNAME_RELEASE    # 4.3 with uname added to
	;;                                  # report: romp-ibm BSD 4.3
    *:BOSX:*:*)
	GUESS=rs6000-bull-bosx
	;;
    DPX/2?00:B.O.S.:*:*)
	GUESS=m68k-bull-sysv3
	;;
    9000/[34]??:4.3bsd:1.*:*)
	GUESS=m68k-hp-bsd
	;;
    hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
	GUESS=m68k-hp-bsd4.4
	;;
    9000/[34678]??:HP-UX:*:*)
	HPUX_REV=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*.[0B]*//'`
	case $UNAME_MACHINE in
	    9000/31?)            HP_ARCH=m68000 ;;
	    9000/[34]??)         HP_ARCH=m68k ;;
	    9000/[678][0-9][0-9])
		if test -x /usr/bin/getconf; then
		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
		    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
		    case $sc_cpu_version in
		      523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0
		      528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1
		      532)                      # CPU_PA_RISC2_0
			case $sc_kernel_bits in
			  32) HP_ARCH=hppa2.0n ;;
			  64) HP_ARCH=hppa2.0w ;;
			  '') HP_ARCH=hppa2.0 ;;   # HP-UX 10.20
			esac ;;
		    esac
		fi
		if test "$HP_ARCH" = ""; then
		    set_cc_for_build
		    sed 's/^		//' << EOF > "$dummy.c"

		#define _HPUX_SOURCE
		#include <stdlib.h>
		#include <unistd.h>

		int main ()
		{
		#if defined(_SC_KERNEL_BITS)
		    long bits = sysconf(_SC_KERNEL_BITS);
		#endif
		    long cpu  = sysconf (_SC_CPU_VERSION);

		    switch (cpu)
			{
			case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
			case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
			case CPU_PA_RISC2_0:
		#if defined(_SC_KERNEL_BITS)
			    switch (bits)
				{
				case 64: puts ("hppa2.0w"); break;
				case 32: puts ("hppa2.0n"); break;
				default: puts ("hppa2.0"); break;
				} break;
		#else  /* !defined(_SC_KERNEL_BITS) */
			    puts ("hppa2.0"); break;
		#endif
			default: puts ("hppa1.0"); break;
			}
		    exit (0);
		}
EOF
		    (CCOPTS="" $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null) && HP_ARCH=`"$dummy"`
		    test -z "$HP_ARCH" && HP_ARCH=hppa
		fi ;;
	esac
	if test "$HP_ARCH" = hppa2.0w
	then
	    set_cc_for_build

	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
	    # generating 64-bit code.  GNU and HP use different nomenclature:
	    #
	    # $ CC_FOR_BUILD=cc ./config.guess
	    # => hppa2.0w-hp-hpux11.23
	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
	    # => hppa64-hp-hpux11.23

	    if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) |
		grep -q __LP64__
	    then
		HP_ARCH=hppa2.0w
	    else
		HP_ARCH=hppa64
	    fi
	fi
	GUESS=$HP_ARCH-hp-hpux$HPUX_REV
	;;
    ia64:HP-UX:*:*)
	HPUX_REV=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*.[0B]*//'`
	GUESS=ia64-hp-hpux$HPUX_REV
	;;
    3050*:HI-UX:*:*)
	set_cc_for_build
	sed 's/^	//' << EOF > "$dummy.c"
	#include <unistd.h>
	int
	main ()
	{
	  long cpu = sysconf (_SC_CPU_VERSION);
	  /* The order matters, because CPU_IS_HP_MC68K erroneously returns
	     true for CPU_PA_RISC1_0.  CPU_IS_PA_RISC returns correct
	     results, however.  */
	  if (CPU_IS_PA_RISC (cpu))
	    {
	      switch (cpu)
		{
		  case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
		  case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
		  case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
		  default: puts ("hppa-hitachi-hiuxwe2"); break;
		}
	    }
	  else if (CPU_IS_HP_MC68K (cpu))
	    puts ("m68k-hitachi-hiuxwe2");
	  else puts ("unknown-hitachi-hiuxwe2");
	  exit (0);
	}
EOF
	$CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` &&
		{ echo "$SYSTEM_NAME"; exit; }
	GUESS=unknown-hitachi-hiuxwe2
	;;
    9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:*)
	GUESS=hppa1.1-hp-bsd
	;;
    9000/8??:4.3bsd:*:*)
	GUESS=hppa1.0-hp-bsd
	;;
    *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
	GUESS=hppa1.0-hp-mpeix
	;;
    hp7??:OSF1:*:* | hp8?[79]:OSF1:*:*)
	GUESS=hppa1.1-hp-osf
	;;
    hp8??:OSF1:*:*)
	GUESS=hppa1.0-hp-osf
	;;
    i*86:OSF1:*:*)
	if test -x /usr/sbin/sysversion ; then
	    GUESS=$UNAME_MACHINE-unknown-osf1mk
	else
	    GUESS=$UNAME_MACHINE-unknown-osf1
	fi
	;;
    parisc*:Lites*:*:*)
	GUESS=hppa1.1-hp-lites
	;;
    C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
	GUESS=c1-convex-bsd
	;;
    C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
	if getsysinfo -f scalar_acc
	then echo c32-convex-bsd
	else echo c2-convex-bsd
	fi
	exit ;;
    C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
	GUESS=c34-convex-bsd
	;;
    C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
	GUESS=c38-convex-bsd
	;;
    C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
	GUESS=c4-convex-bsd
	;;
    CRAY*Y-MP:*:*:*)
	CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'`
	GUESS=ymp-cray-unicos$CRAY_REL
	;;
    CRAY*[A-Z]90:*:*:*)
	echo "$UNAME_MACHINE"-cray-unicos"$UNAME_RELEASE" \
	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
	      -e 's/\.[^.]*$/.X/'
	exit ;;
    CRAY*TS:*:*:*)
	CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'`
	GUESS=t90-cray-unicos$CRAY_REL
	;;
    CRAY*T3E:*:*:*)
	CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'`
	GUESS=alphaev5-cray-unicosmk$CRAY_REL
	;;
    CRAY*SV1:*:*:*)
	CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'`
	GUESS=sv1-cray-unicos$CRAY_REL
	;;
    *:UNICOS/mp:*:*)
	CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'`
	GUESS=craynv-cray-unicosmp$CRAY_REL
	;;
    F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
	FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`
	FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'`
	FUJITSU_REL=`echo "$UNAME_RELEASE" | sed -e 's/ /_/'`
	GUESS=${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}
	;;
    5000:UNIX_System_V:4.*:*)
	FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'`
	FUJITSU_REL=`echo "$UNAME_RELEASE" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'`
	GUESS=sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}
	;;
    i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
	GUESS=$UNAME_MACHINE-pc-bsdi$UNAME_RELEASE
	;;
    sparc*:BSD/OS:*:*)
	GUESS=sparc-unknown-bsdi$UNAME_RELEASE
	;;
    *:BSD/OS:*:*)
	GUESS=$UNAME_MACHINE-unknown-bsdi$UNAME_RELEASE
	;;
    arm:FreeBSD:*:*)
	UNAME_PROCESSOR=`uname -p`
	set_cc_for_build
	if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
	    | grep -q __ARM_PCS_VFP
	then
	    FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'`
	    GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL-gnueabi
	else
	    FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'`
	    GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL-gnueabihf
	fi
	;;
    *:FreeBSD:*:*)
	UNAME_PROCESSOR=`/usr/bin/uname -p`
	case $UNAME_PROCESSOR in
	    amd64)
		UNAME_PROCESSOR=x86_64 ;;
	    i386)
		UNAME_PROCESSOR=i586 ;;
	esac
	FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'`
	GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL
	;;
    i*:CYGWIN*:*)
	GUESS=$UNAME_MACHINE-pc-cygwin
	;;
    *:MINGW64*:*)
	GUESS=$UNAME_MACHINE-pc-mingw64
	;;
    *:MINGW*:*)
	GUESS=$UNAME_MACHINE-pc-mingw32
	;;
    *:MSYS*:*)
	GUESS=$UNAME_MACHINE-pc-msys
	;;
    i*:PW*:*)
	GUESS=$UNAME_MACHINE-pc-pw32
	;;
    *:Interix*:*)
	case $UNAME_MACHINE in
	    x86)
		GUESS=i586-pc-interix$UNAME_RELEASE
		;;
	    authenticamd | genuineintel | EM64T)
		GUESS=x86_64-unknown-interix$UNAME_RELEASE
		;;
	    IA64)
		GUESS=ia64-unknown-interix$UNAME_RELEASE
		;;
	esac ;;
    i*:UWIN*:*)
	GUESS=$UNAME_MACHINE-pc-uwin
	;;
    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
	GUESS=x86_64-pc-cygwin
	;;
    prep*:SunOS:5.*:*)
	SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`
	GUESS=powerpcle-unknown-solaris2$SUN_REL
	;;
    *:GNU:*:*)
	# the GNU system
	GNU_ARCH=`echo "$UNAME_MACHINE" | sed -e 's,[-/].*$,,'`
	GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's,/.*$,,'`
	GUESS=$GNU_ARCH-unknown-$LIBC$GNU_REL
	;;
    *:GNU/*:*:*)
	# other systems with GNU libc and userland
	GNU_SYS=`echo "$UNAME_SYSTEM" | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"`
	GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'`
	GUESS=$UNAME_MACHINE-unknown-$GNU_SYS$GNU_REL-$LIBC
	;;
    *:Minix:*:*)
	GUESS=$UNAME_MACHINE-unknown-minix
	;;
    aarch64:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    aarch64_be:Linux:*:*)
	UNAME_MACHINE=aarch64_be
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    alpha:Linux:*:*)
	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' /proc/cpuinfo 2>/dev/null` in
	  EV5)   UNAME_MACHINE=alphaev5 ;;
	  EV56)  UNAME_MACHINE=alphaev56 ;;
	  PCA56) UNAME_MACHINE=alphapca56 ;;
	  PCA57) UNAME_MACHINE=alphapca56 ;;
	  EV6)   UNAME_MACHINE=alphaev6 ;;
	  EV67)  UNAME_MACHINE=alphaev67 ;;
	  EV68*) UNAME_MACHINE=alphaev68 ;;
	esac
	objdump --private-headers /bin/sh | grep -q ld.so.1
	if test "$?" = 0 ; then LIBC=gnulibc1 ; fi
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    arc:Linux:*:* | arceb:Linux:*:* | arc32:Linux:*:* | arc64:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    arm*:Linux:*:*)
	set_cc_for_build
	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
	    | grep -q __ARM_EABI__
	then
	    GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	else
	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
		| grep -q __ARM_PCS_VFP
	    then
		GUESS=$UNAME_MACHINE-unknown-linux-${LIBC}eabi
	    else
		GUESS=$UNAME_MACHINE-unknown-linux-${LIBC}eabihf
	    fi
	fi
	;;
    avr32*:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    cris:Linux:*:*)
	GUESS=$UNAME_MACHINE-axis-linux-$LIBC
	;;
    crisv32:Linux:*:*)
	GUESS=$UNAME_MACHINE-axis-linux-$LIBC
	;;
    e2k:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    frv:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    hexagon:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    i*86:Linux:*:*)
	GUESS=$UNAME_MACHINE-pc-linux-$LIBC
	;;
    ia64:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    k1om:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    loongarch32:Linux:*:* | loongarch64:Linux:*:* | loongarchx32:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    m32r*:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    m68*:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    mips:Linux:*:* | mips64:Linux:*:*)
	set_cc_for_build
	IS_GLIBC=0
	test x"${LIBC}" = xgnu && IS_GLIBC=1
	sed 's/^	//' << EOF > "$dummy.c"
	#undef CPU
	#undef mips
	#undef mipsel
	#undef mips64
	#undef mips64el
	#if ${IS_GLIBC} && defined(_ABI64)
	LIBCABI=gnuabi64
	#else
	#if ${IS_GLIBC} && defined(_ABIN32)
	LIBCABI=gnuabin32
	#else
	LIBCABI=${LIBC}
	#endif
	#endif

	#if ${IS_GLIBC} && defined(__mips64) && defined(__mips_isa_rev) && __mips_isa_rev>=6
	CPU=mipsisa64r6
	#else
	#if ${IS_GLIBC} && !defined(__mips64) && defined(__mips_isa_rev) && __mips_isa_rev>=6
	CPU=mipsisa32r6
	#else
	#if defined(__mips64)
	CPU=mips64
	#else
	CPU=mips
	#endif
	#endif
	#endif

	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
	MIPS_ENDIAN=el
	#else
	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
	MIPS_ENDIAN=
	#else
	MIPS_ENDIAN=
	#endif
	#endif
EOF
	cc_set_vars=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^CPU\|^MIPS_ENDIAN\|^LIBCABI'`
	eval "$cc_set_vars"
	test "x$CPU" != x && { echo "$CPU${MIPS_ENDIAN}-unknown-linux-$LIBCABI"; exit; }
	;;
    mips64el:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    openrisc*:Linux:*:*)
	GUESS=or1k-unknown-linux-$LIBC
	;;
    or32:Linux:*:* | or1k*:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    padre:Linux:*:*)
	GUESS=sparc-unknown-linux-$LIBC
	;;
    parisc64:Linux:*:* | hppa64:Linux:*:*)
	GUESS=hppa64-unknown-linux-$LIBC
	;;
    parisc:Linux:*:* | hppa:Linux:*:*)
	# Look for CPU level
	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
	  PA7*) GUESS=hppa1.1-unknown-linux-$LIBC ;;
	  PA8*) GUESS=hppa2.0-unknown-linux-$LIBC ;;
	  *)    GUESS=hppa-unknown-linux-$LIBC ;;
	esac
	;;
    ppc64:Linux:*:*)
	GUESS=powerpc64-unknown-linux-$LIBC
	;;
    ppc:Linux:*:*)
	GUESS=powerpc-unknown-linux-$LIBC
	;;
    ppc64le:Linux:*:*)
	GUESS=powerpc64le-unknown-linux-$LIBC
	;;
    ppcle:Linux:*:*)
	GUESS=powerpcle-unknown-linux-$LIBC
	;;
    riscv32:Linux:*:* | riscv32be:Linux:*:* | riscv64:Linux:*:* | riscv64be:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    s390:Linux:*:* | s390x:Linux:*:*)
	GUESS=$UNAME_MACHINE-ibm-linux-$LIBC
	;;
    sh64*:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    sh*:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    sparc:Linux:*:* | sparc64:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    tile*:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    vax:Linux:*:*)
	GUESS=$UNAME_MACHINE-dec-linux-$LIBC
	;;
    x86_64:Linux:*:*)
	set_cc_for_build
	LIBCABI=$LIBC
	if test "$CC_FOR_BUILD" != no_compiler_found; then
	    if (echo '#ifdef __ILP32__'; echo IS_X32; echo '#endif') | \
		(CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
		grep IS_X32 >/dev/null
	    then
		LIBCABI=${LIBC}x32
	    fi
	fi
	GUESS=$UNAME_MACHINE-pc-linux-$LIBCABI
	;;
    xtensa*:Linux:*:*)
	GUESS=$UNAME_MACHINE-unknown-linux-$LIBC
	;;
    i*86:DYNIX/ptx:4*:*)
	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
	# earlier versions are messed up and put the nodename in both
	# sysname and nodename.
	GUESS=i386-sequent-sysv4
	;;
    i*86:UNIX_SV:4.2MP:2.*)
	# Unixware is an offshoot of SVR4, but it has its own version
	# number series starting with 2...
	# I am not positive that other SVR4 systems won't match this,
	# I just have to hope.  -- rms.
	# Use sysv4.2uw... so that sysv4* matches it.
	GUESS=$UNAME_MACHINE-pc-sysv4.2uw$UNAME_VERSION
	;;
    i*86:OS/2:*:*)
	# If we were able to find `uname', then EMX Unix compatibility
	# is probably installed.
	GUESS=$UNAME_MACHINE-pc-os2-emx
	;;
    i*86:XTS-300:*:STOP)
	GUESS=$UNAME_MACHINE-unknown-stop
	;;
    i*86:atheos:*:*)
	GUESS=$UNAME_MACHINE-unknown-atheos
	;;
    i*86:syllable:*:*)
	GUESS=$UNAME_MACHINE-pc-syllable
	;;
    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
	GUESS=i386-unknown-lynxos$UNAME_RELEASE
	;;
    i*86:*DOS:*:*)
	GUESS=$UNAME_MACHINE-pc-msdosdjgpp
	;;
    i*86:*:4.*:*)
	UNAME_REL=`echo "$UNAME_RELEASE" | sed 's/\/MP$//'`
	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
		GUESS=$UNAME_MACHINE-univel-sysv$UNAME_REL
	else
		GUESS=$UNAME_MACHINE-pc-sysv$UNAME_REL
	fi
	;;
    i*86:*:5:[678]*)
	# UnixWare 7.x, OpenUNIX and OpenServer 6.
	case `/bin/uname -X | grep "^Machine"` in
	    *486*)	     UNAME_MACHINE=i486 ;;
	    *Pentium)	     UNAME_MACHINE=i586 ;;
	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
	esac
	GUESS=$UNAME_MACHINE-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
	;;
    i*86:*:3.2:*)
	if test -f /usr/options/cb.name; then
		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
		GUESS=$UNAME_MACHINE-pc-isc$UNAME_REL
	elif /bin/uname -X 2>/dev/null >/dev/null ; then
		UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
		(/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
		(/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
			&& UNAME_MACHINE=i586
		(/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
			&& UNAME_MACHINE=i686
		(/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
			&& UNAME_MACHINE=i686
		GUESS=$UNAME_MACHINE-pc-sco$UNAME_REL
	else
		GUESS=$UNAME_MACHINE-pc-sysv32
	fi
	;;
    pc:*:*:*)
	# Left here for compatibility:
	# uname -m prints for DJGPP always 'pc', but it prints nothing about
	# the processor, so we play safe by assuming i586.
	# Note: whatever this is, it MUST be the same as what config.sub
	# prints for the "djgpp" host, or else GDB configure will decide that
	# this is a cross-build.
	GUESS=i586-pc-msdosdjgpp
	;;
    Intel:Mach:3*:*)
	GUESS=i386-pc-mach3
	;;
    paragon:*:*:*)
	GUESS=i860-intel-osf1
	;;
    i860:*:4.*:*) # i860-SVR4
	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
	  GUESS=i860-stardent-sysv$UNAME_RELEASE    # Stardent Vistra i860-SVR4
	else # Add other i860-SVR4 vendors below as they are discovered.
	  GUESS=i860-unknown-sysv$UNAME_RELEASE     # Unknown i860-SVR4
	fi
	;;
    mini*:CTIX:SYS*5:*)
	# "miniframe"
	GUESS=m68010-convergent-sysv
	;;
    mc68k:UNIX:SYSTEM5:3.51m)
	GUESS=m68k-convergent-sysv
	;;
    M680?0:D-NIX:5.3:*)
	GUESS=m68k-diab-dnix
	;;
    M68*:*:R3V[5678]*:*)
	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
	OS_REL=''
	test -r /etc/.relid \
	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
	  && { echo i486-ncr-sysv4.3"$OS_REL"; exit; }
	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
	  && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;;
    3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
	  && { echo i486-ncr-sysv4; exit; } ;;
    NCR*:*:4.2:* | MPRAS*:*:4.2:*)
	OS_REL='.3'
	test -r /etc/.relid \
	    && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
	    && { echo i486-ncr-sysv4.3"$OS_REL"; exit; }
	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
	    && { echo i586-ncr-sysv4.3"$OS_REL"; exit; }
	/bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
	    && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;;
    m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
	GUESS=m68k-unknown-lynxos$UNAME_RELEASE
	;;
    mc68030:UNIX_System_V:4.*:*)
	GUESS=m68k-atari-sysv4
	;;
    TSUNAMI:LynxOS:2.*:*)
	GUESS=sparc-unknown-lynxos$UNAME_RELEASE
	;;
    rs6000:LynxOS:2.*:*)
	GUESS=rs6000-unknown-lynxos$UNAME_RELEASE
	;;
    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
	GUESS=powerpc-unknown-lynxos$UNAME_RELEASE
	;;
    SM[BE]S:UNIX_SV:*:*)
	GUESS=mips-dde-sysv$UNAME_RELEASE
	;;
    RM*:ReliantUNIX-*:*:*)
	GUESS=mips-sni-sysv4
	;;
    RM*:SINIX-*:*:*)
	GUESS=mips-sni-sysv4
	;;
    *:SINIX-*:*:*)
	if uname -p 2>/dev/null >/dev/null ; then
		UNAME_MACHINE=`(uname -p) 2>/dev/null`
		GUESS=$UNAME_MACHINE-sni-sysv4
	else
		GUESS=ns32k-sni-sysv
	fi
	;;
    PENTIUM:*:4.0*:*)	# Unisys `ClearPath HMP IX 4000' SVR4/MP effort
			# says <Richard.M.Bartel@ccMail.Census.GOV>
	GUESS=i586-unisys-sysv4
	;;
    *:UNIX_System_V:4*:FTX*)
	# From Gerald Hewes <hewes@openmarket.com>.
	# How about differentiating between stratus architectures? -djm
	GUESS=hppa1.1-stratus-sysv4
	;;
    *:*:*:FTX*)
	# From seanf@swdc.stratus.com.
	GUESS=i860-stratus-sysv4
	;;
    i*86:VOS:*:*)
	# From Paul.Green@stratus.com.
	GUESS=$UNAME_MACHINE-stratus-vos
	;;
    *:VOS:*:*)
	# From Paul.Green@stratus.com.
	GUESS=hppa1.1-stratus-vos
	;;
    mc68*:A/UX:*:*)
	GUESS=m68k-apple-aux$UNAME_RELEASE
	;;
    news*:NEWS-OS:6*:*)
	GUESS=mips-sony-newsos6
	;;
    R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
	if test -d /usr/nec; then
		GUESS=mips-nec-sysv$UNAME_RELEASE
	else
		GUESS=mips-unknown-sysv$UNAME_RELEASE
	fi
	;;
    BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
	GUESS=powerpc-be-beos
	;;
    BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
	GUESS=powerpc-apple-beos
	;;
    BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
	GUESS=i586-pc-beos
	;;
    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.
	GUESS=i586-pc-haiku
	;;
    x86_64:Haiku:*:*)
	GUESS=x86_64-unknown-haiku
	;;
    SX-4:SUPER-UX:*:*)
	GUESS=sx4-nec-superux$UNAME_RELEASE
	;;
    SX-5:SUPER-UX:*:*)
	GUESS=sx5-nec-superux$UNAME_RELEASE
	;;
    SX-6:SUPER-UX:*:*)
	GUESS=sx6-nec-superux$UNAME_RELEASE
	;;
    SX-7:SUPER-UX:*:*)
	GUESS=sx7-nec-superux$UNAME_RELEASE
	;;
    SX-8:SUPER-UX:*:*)
	GUESS=sx8-nec-superux$UNAME_RELEASE
	;;
    SX-8R:SUPER-UX:*:*)
	GUESS=sx8r-nec-superux$UNAME_RELEASE
	;;
    SX-ACE:SUPER-UX:*:*)
	GUESS=sxace-nec-superux$UNAME_RELEASE
	;;
    Power*:Rhapsody:*:*)
	GUESS=powerpc-apple-rhapsody$UNAME_RELEASE
	;;
    *:Rhapsody:*:*)
	GUESS=$UNAME_MACHINE-apple-rhapsody$UNAME_RELEASE
	;;
    arm64:Darwin:*:*)
	GUESS=aarch64-apple-darwin$UNAME_RELEASE
	;;
    *:Darwin:*:*)
	UNAME_PROCESSOR=`uname -p`
	case $UNAME_PROCESSOR in
	    unknown) UNAME_PROCESSOR=powerpc ;;
	esac
	if command -v xcode-select > /dev/null 2> /dev/null && \
		! xcode-select --print-path > /dev/null 2> /dev/null ; then
	    # Avoid executing cc if there is no toolchain installed as
	    # cc will be a stub that puts up a graphical alert
	    # prompting the user to install developer tools.
	    CC_FOR_BUILD=no_compiler_found
	else
	    set_cc_for_build
	fi
	if test "$CC_FOR_BUILD" != no_compiler_found; then
	    if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
		   (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
		   grep IS_64BIT_ARCH >/dev/null
	    then
		case $UNAME_PROCESSOR in
		    i386) UNAME_PROCESSOR=x86_64 ;;
		    powerpc) UNAME_PROCESSOR=powerpc64 ;;
		esac
	    fi
	    # On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc
	    if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \
		   (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
		   grep IS_PPC >/dev/null
	    then
		UNAME_PROCESSOR=powerpc
	    fi
	elif test "$UNAME_PROCESSOR" = i386 ; then
	    # uname -m returns i386 or x86_64
	    UNAME_PROCESSOR=$UNAME_MACHINE
	fi
	GUESS=$UNAME_PROCESSOR-apple-darwin$UNAME_RELEASE
	;;
    *:procnto*:*:* | *:QNX:[0123456789]*:*)
	UNAME_PROCESSOR=`uname -p`
	if test "$UNAME_PROCESSOR" = x86; then
		UNAME_PROCESSOR=i386
		UNAME_MACHINE=pc
	fi
	GUESS=$UNAME_PROCESSOR-$UNAME_MACHINE-nto-qnx$UNAME_RELEASE
	;;
    *:QNX:*:4*)
	GUESS=i386-pc-qnx
	;;
    NEO-*:NONSTOP_KERNEL:*:*)
	GUESS=neo-tandem-nsk$UNAME_RELEASE
	;;
    NSE-*:NONSTOP_KERNEL:*:*)
	GUESS=nse-tandem-nsk$UNAME_RELEASE
	;;
    NSR-*:NONSTOP_KERNEL:*:*)
	GUESS=nsr-tandem-nsk$UNAME_RELEASE
	;;
    NSV-*:NONSTOP_KERNEL:*:*)
	GUESS=nsv-tandem-nsk$UNAME_RELEASE
	;;
    NSX-*:NONSTOP_KERNEL:*:*)
	GUESS=nsx-tandem-nsk$UNAME_RELEASE
	;;
    *:NonStop-UX:*:*)
	GUESS=mips-compaq-nonstopux
	;;
    BS2000:POSIX*:*:*)
	GUESS=bs2000-siemens-sysv
	;;
    DS/*:UNIX_System_V:*:*)
	GUESS=$UNAME_MACHINE-$UNAME_SYSTEM-$UNAME_RELEASE
	;;
    *:Plan9:*:*)
	# "uname -m" is not consistent, so use $cputype instead. 386
	# is converted to i386 for consistency with other x86
	# operating systems.
	if test "${cputype-}" = 386; then
	    UNAME_MACHINE=i386
	elif test "x${cputype-}" != x; then
	    UNAME_MACHINE=$cputype
	fi
	GUESS=$UNAME_MACHINE-unknown-plan9
	;;
    *:TOPS-10:*:*)
	GUESS=pdp10-unknown-tops10
	;;
    *:TENEX:*:*)
	GUESS=pdp10-unknown-tenex
	;;
    KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
	GUESS=pdp10-dec-tops20
	;;
    XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
	GUESS=pdp10-xkl-tops20
	;;
    *:TOPS-20:*:*)
	GUESS=pdp10-unknown-tops20
	;;
    *:ITS:*:*)
	GUESS=pdp10-unknown-its
	;;
    SEI:*:*:SEIUX)
	GUESS=mips-sei-seiux$UNAME_RELEASE
	;;
    *:DragonFly:*:*)
	DRAGONFLY_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'`
	GUESS=$UNAME_MACHINE-unknown-dragonfly$DRAGONFLY_REL
	;;
    *:*VMS:*:*)
	UNAME_MACHINE=`(uname -p) 2>/dev/null`
	case $UNAME_MACHINE in
	    A*) GUESS=alpha-dec-vms ;;
	    I*) GUESS=ia64-dec-vms ;;
	    V*) GUESS=vax-dec-vms ;;
	esac ;;
    *:XENIX:*:SysV)
	GUESS=i386-pc-xenix
	;;
    i*86:skyos:*:*)
	SKYOS_REL=`echo "$UNAME_RELEASE" | sed -e 's/ .*$//'`
	GUESS=$UNAME_MACHINE-pc-skyos$SKYOS_REL
	;;
    i*86:rdos:*:*)
	GUESS=$UNAME_MACHINE-pc-rdos
	;;
    *:AROS:*:*)
	GUESS=$UNAME_MACHINE-unknown-aros
	;;
    x86_64:VMkernel:*:*)
	GUESS=$UNAME_MACHINE-unknown-esx
	;;
    amd64:Isilon\ OneFS:*:*)
	GUESS=x86_64-unknown-onefs
	;;
    *:Unleashed:*:*)
	GUESS=$UNAME_MACHINE-unknown-unleashed$UNAME_RELEASE
	;;
esac

# Do we have a guess based on uname results?
if test "x$GUESS" != x; then
    echo "$GUESS"
    exit
fi

# No uname command or uname output not recognized.
set_cc_for_build
cat > "$dummy.c" <<EOF
#ifdef _SEQUENT_
#include <sys/types.h>
#include <sys/utsname.h>
#endif
#if defined(ultrix) || defined(_ultrix) || defined(__ultrix) || defined(__ultrix__)
#if defined (vax) || defined (__vax) || defined (__vax__) || defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__)
#include <signal.h>
#if defined(_SIZE_T_) || defined(SIGLOST)
#include <sys/utsname.h>
#endif
#endif
#endif
main ()
{
#if defined (sony)
#if defined (MIPSEB)
  /* BFD wants "bsd" instead of "newsos".  Perhaps BFD should be changed,
     I don't know....  */
  printf ("mips-sony-bsd\n"); exit (0);
#else
#include <sys/param.h>
  printf ("m68k-sony-newsos%s\n",
#ifdef NEWSOS4
  "4"
#else
  ""
#endif
  ); exit (0);
#endif
#endif

#if defined (NeXT)
#if !defined (__ARCHITECTURE__)
#define __ARCHITECTURE__ "m68k"
#endif
  int version;
  version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
  if (version < 4)
    printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
  else
    printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
  exit (0);
#endif

#if defined (MULTIMAX) || defined (n16)
#if defined (UMAXV)
  printf ("ns32k-encore-sysv\n"); exit (0);
#else
#if defined (CMU)
  printf ("ns32k-encore-mach\n"); exit (0);
#else
  printf ("ns32k-encore-bsd\n"); exit (0);
#endif
#endif
#endif

#if defined (__386BSD__)
  printf ("i386-pc-bsd\n"); exit (0);
#endif

#if defined (sequent)
#if defined (i386)
  printf ("i386-sequent-dynix\n"); exit (0);
#endif
#if defined (ns32000)
  printf ("ns32k-sequent-dynix\n"); exit (0);
#endif
#endif

#if defined (_SEQUENT_)
  struct utsname un;

  uname(&un);
  if (strncmp(un.version, "V2", 2) == 0) {
    printf ("i386-sequent-ptx2\n"); exit (0);
  }
  if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
    printf ("i386-sequent-ptx1\n"); exit (0);
  }
  printf ("i386-sequent-ptx\n"); exit (0);
#endif

#if defined (vax)
#if !defined (ultrix)
#include <sys/param.h>
#if defined (BSD)
#if BSD == 43
  printf ("vax-dec-bsd4.3\n"); exit (0);
#else
#if BSD == 199006
  printf ("vax-dec-bsd4.3reno\n"); exit (0);
#else
  printf ("vax-dec-bsd\n"); exit (0);
#endif
#endif
#else
  printf ("vax-dec-bsd\n"); exit (0);
#endif
#else
#if defined(_SIZE_T_) || defined(SIGLOST)
  struct utsname un;
  uname (&un);
  printf ("vax-dec-ultrix%s\n", un.release); exit (0);
#else
  printf ("vax-dec-ultrix\n"); exit (0);
#endif
#endif
#endif
#if defined(ultrix) || defined(_ultrix) || defined(__ultrix) || defined(__ultrix__)
#if defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__)
#if defined(_SIZE_T_) || defined(SIGLOST)
  struct utsname *un;
  uname (&un);
  printf ("mips-dec-ultrix%s\n", un.release); exit (0);
#else
  printf ("mips-dec-ultrix\n"); exit (0);
#endif
#endif
#endif

#if defined (alliant) && defined (i860)
  printf ("i860-alliant-bsd\n"); exit (0);
#endif

  exit (1);
}
EOF

$CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null && SYSTEM_NAME=`"$dummy"` &&
	{ echo "$SYSTEM_NAME"; exit; }

# Apollos put the system type in the environment.
test -d /usr/apollo && { echo "$ISP-apollo-$SYSTYPE"; exit; }

echo "$0: unable to guess system type" >&2

case $UNAME_MACHINE:$UNAME_SYSTEM in
    mips:Linux | mips64:Linux)
	# If we got here on MIPS GNU/Linux, output extra information.
	cat >&2 <<EOF

NOTE: MIPS GNU/Linux systems require a C compiler to fully recognize
the system type. Please install a C compiler and try again.
EOF
	;;
esac

cat >&2 <<EOF

This script (version $timestamp), has failed to recognize the
operating system you are using. If your script is old, overwrite *all*
copies of config.guess and config.sub with the latest versions from:

  https://git.savannah.gnu.org/cgit/config.git/plain/config.guess
and
  https://git.savannah.gnu.org/cgit/config.git/plain/config.sub
EOF

our_year=`echo $timestamp | sed 's,-.*,,'`
thisyear=`date +%Y`
# shellcheck disable=SC2003
script_age=`expr "$thisyear" - "$our_year"`
if test "$script_age" -lt 3 ; then
   cat >&2 <<EOF

If $0 has already been updated, send the following data and any
information you think might be pertinent to config-patches@gnu.org to
provide the necessary information to handle your system.

config.guess timestamp = $timestamp

uname -m = `(uname -m) 2>/dev/null || echo unknown`
uname -r = `(uname -r) 2>/dev/null || echo unknown`
uname -s = `(uname -s) 2>/dev/null || echo unknown`
uname -v = `(uname -v) 2>/dev/null || echo unknown`

/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
/bin/uname -X     = `(/bin/uname -X) 2>/dev/null`

hostinfo               = `(hostinfo) 2>/dev/null`
/bin/universe          = `(/bin/universe) 2>/dev/null`
/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null`
/bin/arch              = `(/bin/arch) 2>/dev/null`
/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null`
/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`

UNAME_MACHINE = "$UNAME_MACHINE"
UNAME_RELEASE = "$UNAME_RELEASE"
UNAME_SYSTEM  = "$UNAME_SYSTEM"
UNAME_VERSION = "$UNAME_VERSION"
EOF
fi

exit 1

# Local variables:
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "timestamp='"
# time-stamp-format: "%:y-%02m-%02d"
# time-stamp-end: "'"
# End:

Deleted autosetup/autosetup-config.sub.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
671
672
673
674
675
676
677
678
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
737
738
739
740
741
742
743
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
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
817
818
819
820
821
822
823
824
825
826
827
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
860
861
862
863
864
865
866
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
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
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
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
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
1342
1343
1344
1345
1346
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
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
#! /bin/sh
# Configuration validation subroutine script.
#   Copyright 1992-2021 Free Software Foundation, Inc.

# shellcheck disable=SC2006,SC2268 # see below for rationale

timestamp='2021-07-03'

# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <https://www.gnu.org/licenses/>.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that
# program.  This Exception is an additional permission under section 7
# of the GNU General Public License, version 3 ("GPLv3").


# Please send patches to <config-patches@gnu.org>.
#
# Configuration subroutine to validate and canonicalize a configuration type.
# Supply the specified configuration type as an argument.
# If it is invalid, we print an error message on stderr and exit with code 1.
# Otherwise, we print the canonical config type on stdout and succeed.

# You can get the latest version of this script from:
# https://git.savannah.gnu.org/cgit/config.git/plain/config.sub

# This file is supposed to be the same for all GNU packages
# and recognize all the CPU types, system types and aliases
# that are meaningful with *any* GNU software.
# Each package is responsible for reporting which valid configurations
# it does not support.  The user should be able to distinguish
# a failure to support a valid configuration from a meaningless
# configuration.

# The goal of this file is to map all the various variations of a given
# machine specification into a single specification in the form:
#	CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
# or in some cases, the newer four-part form:
#	CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
# It is wrong to echo any other type of specification.

# The "shellcheck disable" line above the timestamp inhibits complaints
# about features and limitations of the classic Bourne shell that were
# superseded or lifted in POSIX.  However, this script identifies a wide
# variety of pre-POSIX systems that do not have POSIX shells at all, and
# even some reasonably current systems (Solaris 10 as case-in-point) still
# have a pre-POSIX /bin/sh.

me=`echo "$0" | sed -e 's,.*/,,'`

usage="\
Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS

Canonicalize a configuration name.

Options:
  -h, --help         print this help, then exit
  -t, --time-stamp   print date of last modification, then exit
  -v, --version      print version number, then exit

Report bugs and patches to <config-patches@gnu.org>."

version="\
GNU config.sub ($timestamp)

Copyright 1992-2021 Free Software Foundation, Inc.

This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."

help="
Try \`$me --help' for more information."

# Parse command line
while test $# -gt 0 ; do
  case $1 in
    --time-stamp | --time* | -t )
       echo "$timestamp" ; exit ;;
    --version | -v )
       echo "$version" ; exit ;;
    --help | --h* | -h )
       echo "$usage"; exit ;;
    -- )     # Stop option processing
       shift; break ;;
    - )	# Use stdin as input.
       break ;;
    -* )
       echo "$me: invalid option $1$help" >&2
       exit 1 ;;

    *local*)
       # First pass through any local machine types.
       echo "$1"
       exit ;;

    * )
       break ;;
  esac
done

case $# in
 0) echo "$me: missing argument$help" >&2
    exit 1;;
 1) ;;
 *) echo "$me: too many arguments$help" >&2
    exit 1;;
esac

# Split fields of configuration type
# shellcheck disable=SC2162
IFS="-" read field1 field2 field3 field4 <<EOF
$1
EOF

# Separate into logical components for further validation
case $1 in
	*-*-*-*-*)
		echo Invalid configuration \`"$1"\': more than four components >&2
		exit 1
		;;
	*-*-*-*)
		basic_machine=$field1-$field2
		basic_os=$field3-$field4
		;;
	*-*-*)
		# Ambiguous whether COMPANY is present, or skipped and KERNEL-OS is two
		# parts
		maybe_os=$field2-$field3
		case $maybe_os in
			nto-qnx* | linux-* | uclinux-uclibc* \
			| uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* \
			| netbsd*-eabi* | kopensolaris*-gnu* | cloudabi*-eabi* \
			| storm-chaos* | os2-emx* | rtmk-nova*)
				basic_machine=$field1
				basic_os=$maybe_os
				;;
			android-linux)
				basic_machine=$field1-unknown
				basic_os=linux-android
				;;
			*)
				basic_machine=$field1-$field2
				basic_os=$field3
				;;
		esac
		;;
	*-*)
		# A lone config we happen to match not fitting any pattern
		case $field1-$field2 in
			decstation-3100)
				basic_machine=mips-dec
				basic_os=
				;;
			*-*)
				# Second component is usually, but not always the OS
				case $field2 in
					# Prevent following clause from handling this valid os
					sun*os*)
						basic_machine=$field1
						basic_os=$field2
						;;
					# Manufacturers
					dec* | mips* | sequent* | encore* | pc533* | sgi* | sony* \
					| att* | 7300* | 3300* | delta* | motorola* | sun[234]* \
					| unicom* | ibm* | next | hp | isi* | apollo | altos* \
					| convergent* | ncr* | news | 32* | 3600* | 3100* \
					| hitachi* | c[123]* | convex* | sun | crds | omron* | dg \
					| ultra | tti* | harris | dolphin | highlevel | gould \
					| cbm | ns | masscomp | apple | axis | knuth | cray \
					| microblaze* | sim | cisco \
					| oki | wec | wrs | winbond)
						basic_machine=$field1-$field2
						basic_os=
						;;
					*)
						basic_machine=$field1
						basic_os=$field2
						;;
				esac
			;;
		esac
		;;
	*)
		# Convert single-component short-hands not valid as part of
		# multi-component configurations.
		case $field1 in
			386bsd)
				basic_machine=i386-pc
				basic_os=bsd
				;;
			a29khif)
				basic_machine=a29k-amd
				basic_os=udi
				;;
			adobe68k)
				basic_machine=m68010-adobe
				basic_os=scout
				;;
			alliant)
				basic_machine=fx80-alliant
				basic_os=
				;;
			altos | altos3068)
				basic_machine=m68k-altos
				basic_os=
				;;
			am29k)
				basic_machine=a29k-none
				basic_os=bsd
				;;
			amdahl)
				basic_machine=580-amdahl
				basic_os=sysv
				;;
			amiga)
				basic_machine=m68k-unknown
				basic_os=
				;;
			amigaos | amigados)
				basic_machine=m68k-unknown
				basic_os=amigaos
				;;
			amigaunix | amix)
				basic_machine=m68k-unknown
				basic_os=sysv4
				;;
			apollo68)
				basic_machine=m68k-apollo
				basic_os=sysv
				;;
			apollo68bsd)
				basic_machine=m68k-apollo
				basic_os=bsd
				;;
			aros)
				basic_machine=i386-pc
				basic_os=aros
				;;
			aux)
				basic_machine=m68k-apple
				basic_os=aux
				;;
			balance)
				basic_machine=ns32k-sequent
				basic_os=dynix
				;;
			blackfin)
				basic_machine=bfin-unknown
				basic_os=linux
				;;
			cegcc)
				basic_machine=arm-unknown
				basic_os=cegcc
				;;
			convex-c1)
				basic_machine=c1-convex
				basic_os=bsd
				;;
			convex-c2)
				basic_machine=c2-convex
				basic_os=bsd
				;;
			convex-c32)
				basic_machine=c32-convex
				basic_os=bsd
				;;
			convex-c34)
				basic_machine=c34-convex
				basic_os=bsd
				;;
			convex-c38)
				basic_machine=c38-convex
				basic_os=bsd
				;;
			cray)
				basic_machine=j90-cray
				basic_os=unicos
				;;
			crds | unos)
				basic_machine=m68k-crds
				basic_os=
				;;
			da30)
				basic_machine=m68k-da30
				basic_os=
				;;
			decstation | pmax | pmin | dec3100 | decstatn)
				basic_machine=mips-dec
				basic_os=
				;;
			delta88)
				basic_machine=m88k-motorola
				basic_os=sysv3
				;;
			dicos)
				basic_machine=i686-pc
				basic_os=dicos
				;;
			djgpp)
				basic_machine=i586-pc
				basic_os=msdosdjgpp
				;;
			ebmon29k)
				basic_machine=a29k-amd
				basic_os=ebmon
				;;
			es1800 | OSE68k | ose68k | ose | OSE)
				basic_machine=m68k-ericsson
				basic_os=ose
				;;
			gmicro)
				basic_machine=tron-gmicro
				basic_os=sysv
				;;
			go32)
				basic_machine=i386-pc
				basic_os=go32
				;;
			h8300hms)
				basic_machine=h8300-hitachi
				basic_os=hms
				;;
			h8300xray)
				basic_machine=h8300-hitachi
				basic_os=xray
				;;
			h8500hms)
				basic_machine=h8500-hitachi
				basic_os=hms
				;;
			harris)
				basic_machine=m88k-harris
				basic_os=sysv3
				;;
			hp300 | hp300hpux)
				basic_machine=m68k-hp
				basic_os=hpux
				;;
			hp300bsd)
				basic_machine=m68k-hp
				basic_os=bsd
				;;
			hppaosf)
				basic_machine=hppa1.1-hp
				basic_os=osf
				;;
			hppro)
				basic_machine=hppa1.1-hp
				basic_os=proelf
				;;
			i386mach)
				basic_machine=i386-mach
				basic_os=mach
				;;
			isi68 | isi)
				basic_machine=m68k-isi
				basic_os=sysv
				;;
			m68knommu)
				basic_machine=m68k-unknown
				basic_os=linux
				;;
			magnum | m3230)
				basic_machine=mips-mips
				basic_os=sysv
				;;
			merlin)
				basic_machine=ns32k-utek
				basic_os=sysv
				;;
			mingw64)
				basic_machine=x86_64-pc
				basic_os=mingw64
				;;
			mingw32)
				basic_machine=i686-pc
				basic_os=mingw32
				;;
			mingw32ce)
				basic_machine=arm-unknown
				basic_os=mingw32ce
				;;
			monitor)
				basic_machine=m68k-rom68k
				basic_os=coff
				;;
			morphos)
				basic_machine=powerpc-unknown
				basic_os=morphos
				;;
			moxiebox)
				basic_machine=moxie-unknown
				basic_os=moxiebox
				;;
			msdos)
				basic_machine=i386-pc
				basic_os=msdos
				;;
			msys)
				basic_machine=i686-pc
				basic_os=msys
				;;
			mvs)
				basic_machine=i370-ibm
				basic_os=mvs
				;;
			nacl)
				basic_machine=le32-unknown
				basic_os=nacl
				;;
			ncr3000)
				basic_machine=i486-ncr
				basic_os=sysv4
				;;
			netbsd386)
				basic_machine=i386-pc
				basic_os=netbsd
				;;
			netwinder)
				basic_machine=armv4l-rebel
				basic_os=linux
				;;
			news | news700 | news800 | news900)
				basic_machine=m68k-sony
				basic_os=newsos
				;;
			news1000)
				basic_machine=m68030-sony
				basic_os=newsos
				;;
			necv70)
				basic_machine=v70-nec
				basic_os=sysv
				;;
			nh3000)
				basic_machine=m68k-harris
				basic_os=cxux
				;;
			nh[45]000)
				basic_machine=m88k-harris
				basic_os=cxux
				;;
			nindy960)
				basic_machine=i960-intel
				basic_os=nindy
				;;
			mon960)
				basic_machine=i960-intel
				basic_os=mon960
				;;
			nonstopux)
				basic_machine=mips-compaq
				basic_os=nonstopux
				;;
			os400)
				basic_machine=powerpc-ibm
				basic_os=os400
				;;
			OSE68000 | ose68000)
				basic_machine=m68000-ericsson
				basic_os=ose
				;;
			os68k)
				basic_machine=m68k-none
				basic_os=os68k
				;;
			paragon)
				basic_machine=i860-intel
				basic_os=osf
				;;
			parisc)
				basic_machine=hppa-unknown
				basic_os=linux
				;;
			psp)
				basic_machine=mipsallegrexel-sony
				basic_os=psp
				;;
			pw32)
				basic_machine=i586-unknown
				basic_os=pw32
				;;
			rdos | rdos64)
				basic_machine=x86_64-pc
				basic_os=rdos
				;;
			rdos32)
				basic_machine=i386-pc
				basic_os=rdos
				;;
			rom68k)
				basic_machine=m68k-rom68k
				basic_os=coff
				;;
			sa29200)
				basic_machine=a29k-amd
				basic_os=udi
				;;
			sei)
				basic_machine=mips-sei
				basic_os=seiux
				;;
			sequent)
				basic_machine=i386-sequent
				basic_os=
				;;
			sps7)
				basic_machine=m68k-bull
				basic_os=sysv2
				;;
			st2000)
				basic_machine=m68k-tandem
				basic_os=
				;;
			stratus)
				basic_machine=i860-stratus
				basic_os=sysv4
				;;
			sun2)
				basic_machine=m68000-sun
				basic_os=
				;;
			sun2os3)
				basic_machine=m68000-sun
				basic_os=sunos3
				;;
			sun2os4)
				basic_machine=m68000-sun
				basic_os=sunos4
				;;
			sun3)
				basic_machine=m68k-sun
				basic_os=
				;;
			sun3os3)
				basic_machine=m68k-sun
				basic_os=sunos3
				;;
			sun3os4)
				basic_machine=m68k-sun
				basic_os=sunos4
				;;
			sun4)
				basic_machine=sparc-sun
				basic_os=
				;;
			sun4os3)
				basic_machine=sparc-sun
				basic_os=sunos3
				;;
			sun4os4)
				basic_machine=sparc-sun
				basic_os=sunos4
				;;
			sun4sol2)
				basic_machine=sparc-sun
				basic_os=solaris2
				;;
			sun386 | sun386i | roadrunner)
				basic_machine=i386-sun
				basic_os=
				;;
			sv1)
				basic_machine=sv1-cray
				basic_os=unicos
				;;
			symmetry)
				basic_machine=i386-sequent
				basic_os=dynix
				;;
			t3e)
				basic_machine=alphaev5-cray
				basic_os=unicos
				;;
			t90)
				basic_machine=t90-cray
				basic_os=unicos
				;;
			toad1)
				basic_machine=pdp10-xkl
				basic_os=tops20
				;;
			tpf)
				basic_machine=s390x-ibm
				basic_os=tpf
				;;
			udi29k)
				basic_machine=a29k-amd
				basic_os=udi
				;;
			ultra3)
				basic_machine=a29k-nyu
				basic_os=sym1
				;;
			v810 | necv810)
				basic_machine=v810-nec
				basic_os=none
				;;
			vaxv)
				basic_machine=vax-dec
				basic_os=sysv
				;;
			vms)
				basic_machine=vax-dec
				basic_os=vms
				;;
			vsta)
				basic_machine=i386-pc
				basic_os=vsta
				;;
			vxworks960)
				basic_machine=i960-wrs
				basic_os=vxworks
				;;
			vxworks68)
				basic_machine=m68k-wrs
				basic_os=vxworks
				;;
			vxworks29k)
				basic_machine=a29k-wrs
				basic_os=vxworks
				;;
			xbox)
				basic_machine=i686-pc
				basic_os=mingw32
				;;
			ymp)
				basic_machine=ymp-cray
				basic_os=unicos
				;;
			*)
				basic_machine=$1
				basic_os=
				;;
		esac
		;;
esac

# Decode 1-component or ad-hoc basic machines
case $basic_machine in
	# Here we handle the default manufacturer of certain CPU types.  It is in
	# some cases the only manufacturer, in others, it is the most popular.
	w89k)
		cpu=hppa1.1
		vendor=winbond
		;;
	op50n)
		cpu=hppa1.1
		vendor=oki
		;;
	op60c)
		cpu=hppa1.1
		vendor=oki
		;;
	ibm*)
		cpu=i370
		vendor=ibm
		;;
	orion105)
		cpu=clipper
		vendor=highlevel
		;;
	mac | mpw | mac-mpw)
		cpu=m68k
		vendor=apple
		;;
	pmac | pmac-mpw)
		cpu=powerpc
		vendor=apple
		;;

	# Recognize the various machine names and aliases which stand
	# for a CPU type and a company and sometimes even an OS.
	3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
		cpu=m68000
		vendor=att
		;;
	3b*)
		cpu=we32k
		vendor=att
		;;
	bluegene*)
		cpu=powerpc
		vendor=ibm
		basic_os=cnk
		;;
	decsystem10* | dec10*)
		cpu=pdp10
		vendor=dec
		basic_os=tops10
		;;
	decsystem20* | dec20*)
		cpu=pdp10
		vendor=dec
		basic_os=tops20
		;;
	delta | 3300 | motorola-3300 | motorola-delta \
	      | 3300-motorola | delta-motorola)
		cpu=m68k
		vendor=motorola
		;;
	dpx2*)
		cpu=m68k
		vendor=bull
		basic_os=sysv3
		;;
	encore | umax | mmax)
		cpu=ns32k
		vendor=encore
		;;
	elxsi)
		cpu=elxsi
		vendor=elxsi
		basic_os=${basic_os:-bsd}
		;;
	fx2800)
		cpu=i860
		vendor=alliant
		;;
	genix)
		cpu=ns32k
		vendor=ns
		;;
	h3050r* | hiux*)
		cpu=hppa1.1
		vendor=hitachi
		basic_os=hiuxwe2
		;;
	hp3k9[0-9][0-9] | hp9[0-9][0-9])
		cpu=hppa1.0
		vendor=hp
		;;
	hp9k2[0-9][0-9] | hp9k31[0-9])
		cpu=m68000
		vendor=hp
		;;
	hp9k3[2-9][0-9])
		cpu=m68k
		vendor=hp
		;;
	hp9k6[0-9][0-9] | hp6[0-9][0-9])
		cpu=hppa1.0
		vendor=hp
		;;
	hp9k7[0-79][0-9] | hp7[0-79][0-9])
		cpu=hppa1.1
		vendor=hp
		;;
	hp9k78[0-9] | hp78[0-9])
		# FIXME: really hppa2.0-hp
		cpu=hppa1.1
		vendor=hp
		;;
	hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
		# FIXME: really hppa2.0-hp
		cpu=hppa1.1
		vendor=hp
		;;
	hp9k8[0-9][13679] | hp8[0-9][13679])
		cpu=hppa1.1
		vendor=hp
		;;
	hp9k8[0-9][0-9] | hp8[0-9][0-9])
		cpu=hppa1.0
		vendor=hp
		;;
	i*86v32)
		cpu=`echo "$1" | sed -e 's/86.*/86/'`
		vendor=pc
		basic_os=sysv32
		;;
	i*86v4*)
		cpu=`echo "$1" | sed -e 's/86.*/86/'`
		vendor=pc
		basic_os=sysv4
		;;
	i*86v)
		cpu=`echo "$1" | sed -e 's/86.*/86/'`
		vendor=pc
		basic_os=sysv
		;;
	i*86sol2)
		cpu=`echo "$1" | sed -e 's/86.*/86/'`
		vendor=pc
		basic_os=solaris2
		;;
	j90 | j90-cray)
		cpu=j90
		vendor=cray
		basic_os=${basic_os:-unicos}
		;;
	iris | iris4d)
		cpu=mips
		vendor=sgi
		case $basic_os in
		    irix*)
			;;
		    *)
			basic_os=irix4
			;;
		esac
		;;
	miniframe)
		cpu=m68000
		vendor=convergent
		;;
	*mint | mint[0-9]* | *MiNT | *MiNT[0-9]*)
		cpu=m68k
		vendor=atari
		basic_os=mint
		;;
	news-3600 | risc-news)
		cpu=mips
		vendor=sony
		basic_os=newsos
		;;
	next | m*-next)
		cpu=m68k
		vendor=next
		case $basic_os in
		    openstep*)
		        ;;
		    nextstep*)
			;;
		    ns2*)
		      basic_os=nextstep2
			;;
		    *)
		      basic_os=nextstep3
			;;
		esac
		;;
	np1)
		cpu=np1
		vendor=gould
		;;
	op50n-* | op60c-*)
		cpu=hppa1.1
		vendor=oki
		basic_os=proelf
		;;
	pa-hitachi)
		cpu=hppa1.1
		vendor=hitachi
		basic_os=hiuxwe2
		;;
	pbd)
		cpu=sparc
		vendor=tti
		;;
	pbb)
		cpu=m68k
		vendor=tti
		;;
	pc532)
		cpu=ns32k
		vendor=pc532
		;;
	pn)
		cpu=pn
		vendor=gould
		;;
	power)
		cpu=power
		vendor=ibm
		;;
	ps2)
		cpu=i386
		vendor=ibm
		;;
	rm[46]00)
		cpu=mips
		vendor=siemens
		;;
	rtpc | rtpc-*)
		cpu=romp
		vendor=ibm
		;;
	sde)
		cpu=mipsisa32
		vendor=sde
		basic_os=${basic_os:-elf}
		;;
	simso-wrs)
		cpu=sparclite
		vendor=wrs
		basic_os=vxworks
		;;
	tower | tower-32)
		cpu=m68k
		vendor=ncr
		;;
	vpp*|vx|vx-*)
		cpu=f301
		vendor=fujitsu
		;;
	w65)
		cpu=w65
		vendor=wdc
		;;
	w89k-*)
		cpu=hppa1.1
		vendor=winbond
		basic_os=proelf
		;;
	none)
		cpu=none
		vendor=none
		;;
	leon|leon[3-9])
		cpu=sparc
		vendor=$basic_machine
		;;
	leon-*|leon[3-9]-*)
		cpu=sparc
		vendor=`echo "$basic_machine" | sed 's/-.*//'`
		;;

	*-*)
		# shellcheck disable=SC2162
		IFS="-" read cpu vendor <<EOF
$basic_machine
EOF
		;;
	# We use `pc' rather than `unknown'
	# because (1) that's what they normally are, and
	# (2) the word "unknown" tends to confuse beginning users.
	i*86 | x86_64)
		cpu=$basic_machine
		vendor=pc
		;;
	# These rules are duplicated from below for sake of the special case above;
	# i.e. things that normalized to x86 arches should also default to "pc"
	pc98)
		cpu=i386
		vendor=pc
		;;
	x64 | amd64)
		cpu=x86_64
		vendor=pc
		;;
	# Recognize the basic CPU types without company name.
	*)
		cpu=$basic_machine
		vendor=unknown
		;;
esac

unset -v basic_machine

# Decode basic machines in the full and proper CPU-Company form.
case $cpu-$vendor in
	# Here we handle the default manufacturer of certain CPU types in canonical form. It is in
	# some cases the only manufacturer, in others, it is the most popular.
	craynv-unknown)
		vendor=cray
		basic_os=${basic_os:-unicosmp}
		;;
	c90-unknown | c90-cray)
		vendor=cray
		basic_os=${Basic_os:-unicos}
		;;
	fx80-unknown)
		vendor=alliant
		;;
	romp-unknown)
		vendor=ibm
		;;
	mmix-unknown)
		vendor=knuth
		;;
	microblaze-unknown | microblazeel-unknown)
		vendor=xilinx
		;;
	rs6000-unknown)
		vendor=ibm
		;;
	vax-unknown)
		vendor=dec
		;;
	pdp11-unknown)
		vendor=dec
		;;
	we32k-unknown)
		vendor=att
		;;
	cydra-unknown)
		vendor=cydrome
		;;
	i370-ibm*)
		vendor=ibm
		;;
	orion-unknown)
		vendor=highlevel
		;;
	xps-unknown | xps100-unknown)
		cpu=xps100
		vendor=honeywell
		;;

	# Here we normalize CPU types with a missing or matching vendor
	dpx20-unknown | dpx20-bull)
		cpu=rs6000
		vendor=bull
		basic_os=${basic_os:-bosx}
		;;

	# Here we normalize CPU types irrespective of the vendor
	amd64-*)
		cpu=x86_64
		;;
	blackfin-*)
		cpu=bfin
		basic_os=linux
		;;
	c54x-*)
		cpu=tic54x
		;;
	c55x-*)
		cpu=tic55x
		;;
	c6x-*)
		cpu=tic6x
		;;
	e500v[12]-*)
		cpu=powerpc
		basic_os=${basic_os}"spe"
		;;
	mips3*-*)
		cpu=mips64
		;;
	ms1-*)
		cpu=mt
		;;
	m68knommu-*)
		cpu=m68k
		basic_os=linux
		;;
	m9s12z-* | m68hcs12z-* | hcs12z-* | s12z-*)
		cpu=s12z
		;;
	openrisc-*)
		cpu=or32
		;;
	parisc-*)
		cpu=hppa
		basic_os=linux
		;;
	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
		cpu=i586
		;;
	pentiumpro-* | p6-* | 6x86-* | athlon-* | athalon_*-*)
		cpu=i686
		;;
	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
		cpu=i686
		;;
	pentium4-*)
		cpu=i786
		;;
	pc98-*)
		cpu=i386
		;;
	ppc-* | ppcbe-*)
		cpu=powerpc
		;;
	ppcle-* | powerpclittle-*)
		cpu=powerpcle
		;;
	ppc64-*)
		cpu=powerpc64
		;;
	ppc64le-* | powerpc64little-*)
		cpu=powerpc64le
		;;
	sb1-*)
		cpu=mipsisa64sb1
		;;
	sb1el-*)
		cpu=mipsisa64sb1el
		;;
	sh5e[lb]-*)
		cpu=`echo "$cpu" | sed 's/^\(sh.\)e\(.\)$/\1\2e/'`
		;;
	spur-*)
		cpu=spur
		;;
	strongarm-* | thumb-*)
		cpu=arm
		;;
	tx39-*)
		cpu=mipstx39
		;;
	tx39el-*)
		cpu=mipstx39el
		;;
	x64-*)
		cpu=x86_64
		;;
	xscale-* | xscalee[bl]-*)
		cpu=`echo "$cpu" | sed 's/^xscale/arm/'`
		;;
	arm64-*)
		cpu=aarch64
		;;

	# Recognize the canonical CPU Types that limit and/or modify the
	# company names they are paired with.
	cr16-*)
		basic_os=${basic_os:-elf}
		;;
	crisv32-* | etraxfs*-*)
		cpu=crisv32
		vendor=axis
		;;
	cris-* | etrax*-*)
		cpu=cris
		vendor=axis
		;;
	crx-*)
		basic_os=${basic_os:-elf}
		;;
	neo-tandem)
		cpu=neo
		vendor=tandem
		;;
	nse-tandem)
		cpu=nse
		vendor=tandem
		;;
	nsr-tandem)
		cpu=nsr
		vendor=tandem
		;;
	nsv-tandem)
		cpu=nsv
		vendor=tandem
		;;
	nsx-tandem)
		cpu=nsx
		vendor=tandem
		;;
	mipsallegrexel-sony)
		cpu=mipsallegrexel
		vendor=sony
		;;
	tile*-*)
		basic_os=${basic_os:-linux-gnu}
		;;

	*)
		# Recognize the canonical CPU types that are allowed with any
		# company name.
		case $cpu in
			1750a | 580 \
			| a29k \
			| aarch64 | aarch64_be \
			| abacus \
			| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] \
			| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] \
			| alphapca5[67] | alpha64pca5[67] \
			| am33_2.0 \
			| amdgcn \
			| arc | arceb | arc32 | arc64 \
			| arm | arm[lb]e | arme[lb] | armv* \
			| avr | avr32 \
			| asmjs \
			| ba \
			| be32 | be64 \
			| bfin | bpf | bs2000 \
			| c[123]* | c30 | [cjt]90 | c4x \
			| c8051 | clipper | craynv | csky | cydra \
			| d10v | d30v | dlx | dsp16xx \
			| e2k | elxsi | epiphany \
			| f30[01] | f700 | fido | fr30 | frv | ft32 | fx80 \
			| h8300 | h8500 \
			| hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
			| hexagon \
			| i370 | i*86 | i860 | i960 | ia16 | ia64 \
			| ip2k | iq2000 \
			| k1om \
			| le32 | le64 \
			| lm32 \
			| loongarch32 | loongarch64 | loongarchx32 \
			| m32c | m32r | m32rle \
			| m5200 | m68000 | m680[012346]0 | m68360 | m683?2 | m68k \
			| m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x \
			| m88110 | m88k | maxq | mb | mcore | mep | metag \
			| microblaze | microblazeel \
			| mips | mipsbe | mipseb | mipsel | mipsle \
			| mips16 \
			| mips64 | mips64eb | mips64el \
			| mips64octeon | mips64octeonel \
			| mips64orion | mips64orionel \
			| mips64r5900 | mips64r5900el \
			| mips64vr | mips64vrel \
			| mips64vr4100 | mips64vr4100el \
			| mips64vr4300 | mips64vr4300el \
			| mips64vr5000 | mips64vr5000el \
			| mips64vr5900 | mips64vr5900el \
			| mipsisa32 | mipsisa32el \
			| mipsisa32r2 | mipsisa32r2el \
			| mipsisa32r3 | mipsisa32r3el \
			| mipsisa32r5 | mipsisa32r5el \
			| mipsisa32r6 | mipsisa32r6el \
			| mipsisa64 | mipsisa64el \
			| mipsisa64r2 | mipsisa64r2el \
			| mipsisa64r3 | mipsisa64r3el \
			| mipsisa64r5 | mipsisa64r5el \
			| mipsisa64r6 | mipsisa64r6el \
			| mipsisa64sb1 | mipsisa64sb1el \
			| mipsisa64sr71k | mipsisa64sr71kel \
			| mipsr5900 | mipsr5900el \
			| mipstx39 | mipstx39el \
			| mmix \
			| mn10200 | mn10300 \
			| moxie \
			| mt \
			| msp430 \
			| nds32 | nds32le | nds32be \
			| nfp \
			| nios | nios2 | nios2eb | nios2el \
			| none | np1 | ns16k | ns32k | nvptx \
			| open8 \
			| or1k* \
			| or32 \
			| orion \
			| picochip \
			| pdp10 | pdp11 | pj | pjl | pn | power \
			| powerpc | powerpc64 | powerpc64le | powerpcle | powerpcspe \
			| pru \
			| pyramid \
			| riscv | riscv32 | riscv32be | riscv64 | riscv64be \
			| rl78 | romp | rs6000 | rx \
			| s390 | s390x \
			| score \
			| sh | shl \
			| sh[1234] | sh[24]a | sh[24]ae[lb] | sh[23]e | she[lb] | sh[lb]e \
			| sh[1234]e[lb] |  sh[12345][lb]e | sh[23]ele | sh64 | sh64le \
			| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet \
			| sparclite \
			| sparcv8 | sparcv9 | sparcv9b | sparcv9v | sv1 | sx* \
			| spu \
			| tahoe \
			| thumbv7* \
			| tic30 | tic4x | tic54x | tic55x | tic6x | tic80 \
			| tron \
			| ubicom32 \
			| v70 | v850 | v850e | v850e1 | v850es | v850e2 | v850e2v3 \
			| vax \
			| visium \
			| w65 \
			| wasm32 | wasm64 \
			| we32k \
			| x86 | x86_64 | xc16x | xgate | xps100 \
			| xstormy16 | xtensa* \
			| ymp \
			| z8k | z80)
				;;

			*)
				echo Invalid configuration \`"$1"\': machine \`"$cpu-$vendor"\' not recognized 1>&2
				exit 1
				;;
		esac
		;;
esac

# Here we canonicalize certain aliases for manufacturers.
case $vendor in
	digital*)
		vendor=dec
		;;
	commodore*)
		vendor=cbm
		;;
	*)
		;;
esac

# Decode manufacturer-specific aliases for certain operating systems.

if test x$basic_os != x
then

# First recognize some ad-hoc caes, or perhaps split kernel-os, or else just
# set os.
case $basic_os in
	gnu/linux*)
		kernel=linux
		os=`echo "$basic_os" | sed -e 's|gnu/linux|gnu|'`
		;;
	os2-emx)
		kernel=os2
		os=`echo "$basic_os" | sed -e 's|os2-emx|emx|'`
		;;
	nto-qnx*)
		kernel=nto
		os=`echo "$basic_os" | sed -e 's|nto-qnx|qnx|'`
		;;
	*-*)
		# shellcheck disable=SC2162
		IFS="-" read kernel os <<EOF
$basic_os
EOF
		;;
	# Default OS when just kernel was specified
	nto*)
		kernel=nto
		os=`echo "$basic_os" | sed -e 's|nto|qnx|'`
		;;
	linux*)
		kernel=linux
		os=`echo "$basic_os" | sed -e 's|linux|gnu|'`
		;;
	*)
		kernel=
		os=$basic_os
		;;
esac

# Now, normalize the OS (knowing we just have one component, it's not a kernel,
# etc.)
case $os in
	# First match some system type aliases that might get confused
	# with valid system types.
	# solaris* is a basic system type, with this one exception.
	auroraux)
		os=auroraux
		;;
	bluegene*)
		os=cnk
		;;
	solaris1 | solaris1.*)
		os=`echo "$os" | sed -e 's|solaris1|sunos4|'`
		;;
	solaris)
		os=solaris2
		;;
	unixware*)
		os=sysv4.2uw
		;;
	# es1800 is here to avoid being matched by es* (a different OS)
	es1800*)
		os=ose
		;;
	# Some version numbers need modification
	chorusos*)
		os=chorusos
		;;
	isc)
		os=isc2.2
		;;
	sco6)
		os=sco5v6
		;;
	sco5)
		os=sco3.2v5
		;;
	sco4)
		os=sco3.2v4
		;;
	sco3.2.[4-9]*)
		os=`echo "$os" | sed -e 's/sco3.2./sco3.2v/'`
		;;
	sco*v* | scout)
		# Don't match below
		;;
	sco*)
		os=sco3.2v2
		;;
	psos*)
		os=psos
		;;
	qnx*)
		os=qnx
		;;
	hiux*)
		os=hiuxwe2
		;;
	lynx*178)
		os=lynxos178
		;;
	lynx*5)
		os=lynxos5
		;;
	lynxos*)
		# don't get caught up in next wildcard
		;;
	lynx*)
		os=lynxos
		;;
	mac[0-9]*)
		os=`echo "$os" | sed -e 's|mac|macos|'`
		;;
	opened*)
		os=openedition
		;;
	os400*)
		os=os400
		;;
	sunos5*)
		os=`echo "$os" | sed -e 's|sunos5|solaris2|'`
		;;
	sunos6*)
		os=`echo "$os" | sed -e 's|sunos6|solaris3|'`
		;;
	wince*)
		os=wince
		;;
	utek*)
		os=bsd
		;;
	dynix*)
		os=bsd
		;;
	acis*)
		os=aos
		;;
	atheos*)
		os=atheos
		;;
	syllable*)
		os=syllable
		;;
	386bsd)
		os=bsd
		;;
	ctix* | uts*)
		os=sysv
		;;
	nova*)
		os=rtmk-nova
		;;
	ns2)
		os=nextstep2
		;;
	# Preserve the version number of sinix5.
	sinix5.*)
		os=`echo "$os" | sed -e 's|sinix|sysv|'`
		;;
	sinix*)
		os=sysv4
		;;
	tpf*)
		os=tpf
		;;
	triton*)
		os=sysv3
		;;
	oss*)
		os=sysv3
		;;
	svr4*)
		os=sysv4
		;;
	svr3)
		os=sysv3
		;;
	sysvr4)
		os=sysv4
		;;
	ose*)
		os=ose
		;;
	*mint | mint[0-9]* | *MiNT | MiNT[0-9]*)
		os=mint
		;;
	dicos*)
		os=dicos
		;;
	pikeos*)
		# Until real need of OS specific support for
		# particular features comes up, bare metal
		# configurations are quite functional.
		case $cpu in
		    arm*)
			os=eabi
			;;
		    *)
			os=elf
			;;
		esac
		;;
	*)
		# No normalization, but not necessarily accepted, that comes below.
		;;
esac

else

# Here we handle the default operating systems that come with various machines.
# The value should be what the vendor currently ships out the door with their
# machine or put another way, the most popular os provided with the machine.

# Note that if you're going to try to match "-MANUFACTURER" here (say,
# "-sun"), then you have to tell the case statement up towards the top
# that MANUFACTURER isn't an operating system.  Otherwise, code above
# will signal an error saying that MANUFACTURER isn't an operating
# system, and we'll never get to this point.

kernel=
case $cpu-$vendor in
	score-*)
		os=elf
		;;
	spu-*)
		os=elf
		;;
	*-acorn)
		os=riscix1.2
		;;
	arm*-rebel)
		kernel=linux
		os=gnu
		;;
	arm*-semi)
		os=aout
		;;
	c4x-* | tic4x-*)
		os=coff
		;;
	c8051-*)
		os=elf
		;;
	clipper-intergraph)
		os=clix
		;;
	hexagon-*)
		os=elf
		;;
	tic54x-*)
		os=coff
		;;
	tic55x-*)
		os=coff
		;;
	tic6x-*)
		os=coff
		;;
	# This must come before the *-dec entry.
	pdp10-*)
		os=tops20
		;;
	pdp11-*)
		os=none
		;;
	*-dec | vax-*)
		os=ultrix4.2
		;;
	m68*-apollo)
		os=domain
		;;
	i386-sun)
		os=sunos4.0.2
		;;
	m68000-sun)
		os=sunos3
		;;
	m68*-cisco)
		os=aout
		;;
	mep-*)
		os=elf
		;;
	mips*-cisco)
		os=elf
		;;
	mips*-*)
		os=elf
		;;
	or32-*)
		os=coff
		;;
	*-tti)	# must be before sparc entry or we get the wrong os.
		os=sysv3
		;;
	sparc-* | *-sun)
		os=sunos4.1.1
		;;
	pru-*)
		os=elf
		;;
	*-be)
		os=beos
		;;
	*-ibm)
		os=aix
		;;
	*-knuth)
		os=mmixware
		;;
	*-wec)
		os=proelf
		;;
	*-winbond)
		os=proelf
		;;
	*-oki)
		os=proelf
		;;
	*-hp)
		os=hpux
		;;
	*-hitachi)
		os=hiux
		;;
	i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
		os=sysv
		;;
	*-cbm)
		os=amigaos
		;;
	*-dg)
		os=dgux
		;;
	*-dolphin)
		os=sysv3
		;;
	m68k-ccur)
		os=rtu
		;;
	m88k-omron*)
		os=luna
		;;
	*-next)
		os=nextstep
		;;
	*-sequent)
		os=ptx
		;;
	*-crds)
		os=unos
		;;
	*-ns)
		os=genix
		;;
	i370-*)
		os=mvs
		;;
	*-gould)
		os=sysv
		;;
	*-highlevel)
		os=bsd
		;;
	*-encore)
		os=bsd
		;;
	*-sgi)
		os=irix
		;;
	*-siemens)
		os=sysv4
		;;
	*-masscomp)
		os=rtu
		;;
	f30[01]-fujitsu | f700-fujitsu)
		os=uxpv
		;;
	*-rom68k)
		os=coff
		;;
	*-*bug)
		os=coff
		;;
	*-apple)
		os=macos
		;;
	*-atari*)
		os=mint
		;;
	*-wrs)
		os=vxworks
		;;
	*)
		os=none
		;;
esac

fi

# Now, validate our (potentially fixed-up) OS.
case $os in
	# Sometimes we do "kernel-libc", so those need to count as OSes.
	musl* | newlib* | uclibc*)
		;;
	# Likewise for "kernel-abi"
	eabi* | gnueabi*)
		;;
	# VxWorks passes extra cpu info in the 4th filed.
	simlinux | simwindows | spe)
		;;
	# Now accept the basic system types.
	# The portable systems comes first.
	# Each alternative MUST end in a * to match a version number.
	gnu* | android* | bsd* | mach* | minix* | genix* | ultrix* | irix* \
	     | *vms* | esix* | aix* | cnk* | sunos | sunos[34]* \
	     | hpux* | unos* | osf* | luna* | dgux* | auroraux* | solaris* \
	     | sym* |  plan9* | psp* | sim* | xray* | os68k* | v88r* \
	     | hiux* | abug | nacl* | netware* | windows* \
	     | os9* | macos* | osx* | ios* \
	     | mpw* | magic* | mmixware* | mon960* | lnews* \
	     | amigaos* | amigados* | msdos* | newsos* | unicos* | aof* \
	     | aos* | aros* | cloudabi* | sortix* | twizzler* \
	     | nindy* | vxsim* | vxworks* | ebmon* | hms* | mvs* \
	     | clix* | riscos* | uniplus* | iris* | isc* | rtu* | xenix* \
	     | mirbsd* | netbsd* | dicos* | openedition* | ose* \
	     | bitrig* | openbsd* | secbsd* | solidbsd* | libertybsd* | os108* \
	     | ekkobsd* | freebsd* | riscix* | lynxos* | os400* \
	     | bosx* | nextstep* | cxux* | aout* | elf* | oabi* \
	     | ptx* | coff* | ecoff* | winnt* | domain* | vsta* \
	     | udi* | lites* | ieee* | go32* | aux* | hcos* \
	     | chorusrdb* | cegcc* | glidix* | serenity* \
	     | cygwin* | msys* | pe* | moss* | proelf* | rtems* \
	     | midipix* | mingw32* | mingw64* | mint* \
	     | uxpv* | beos* | mpeix* | udk* | moxiebox* \
	     | interix* | uwin* | mks* | rhapsody* | darwin* \
	     | openstep* | oskit* | conix* | pw32* | nonstopux* \
	     | storm-chaos* | tops10* | tenex* | tops20* | its* \
	     | os2* | vos* | palmos* | uclinux* | nucleus* | morphos* \
	     | scout* | superux* | sysv* | rtmk* | tpf* | windiss* \
	     | powermax* | dnix* | nx6 | nx7 | sei* | dragonfly* \
	     | skyos* | haiku* | rdos* | toppers* | drops* | es* \
	     | onefs* | tirtos* | phoenix* | fuchsia* | redox* | bme* \
	     | midnightbsd* | amdhsa* | unleashed* | emscripten* | wasi* \
	     | nsk* | powerunix* | genode* | zvmoe* | qnx* | emx*)
		;;
	# This one is extra strict with allowed versions
	sco3.2v2 | sco3.2v[4-9]* | sco5v6*)
		# Don't forget version if it is 3.2v4 or newer.
		;;
	none)
		;;
	*)
		echo Invalid configuration \`"$1"\': OS \`"$os"\' not recognized 1>&2
		exit 1
		;;
esac

# As a final step for OS-related things, validate the OS-kernel combination
# (given a valid OS), if there is a kernel.
case $kernel-$os in
	linux-gnu* | linux-dietlibc* | linux-android* | linux-newlib* | linux-musl* | linux-uclibc* )
		;;
	uclinux-uclibc* )
		;;
	-dietlibc* | -newlib* | -musl* | -uclibc* )
		# These are just libc implementations, not actual OSes, and thus
		# require a kernel.
		echo "Invalid configuration \`$1': libc \`$os' needs explicit kernel." 1>&2
		exit 1
		;;
	kfreebsd*-gnu* | kopensolaris*-gnu*)
		;;
	vxworks-simlinux | vxworks-simwindows | vxworks-spe)
		;;
	nto-qnx*)
		;;
	os2-emx)
		;;
	*-eabi* | *-gnueabi*)
		;;
	-*)
		# Blank kernel with real OS is always fine.
		;;
	*-*)
		echo "Invalid configuration \`$1': Kernel \`$kernel' not known to work with OS \`$os'." 1>&2
		exit 1
		;;
esac

# Here we handle the case where we know the os, and the CPU type, but not the
# manufacturer.  We pick the logical manufacturer.
case $vendor in
	unknown)
		case $cpu-$os in
			*-riscix*)
				vendor=acorn
				;;
			*-sunos*)
				vendor=sun
				;;
			*-cnk* | *-aix*)
				vendor=ibm
				;;
			*-beos*)
				vendor=be
				;;
			*-hpux*)
				vendor=hp
				;;
			*-mpeix*)
				vendor=hp
				;;
			*-hiux*)
				vendor=hitachi
				;;
			*-unos*)
				vendor=crds
				;;
			*-dgux*)
				vendor=dg
				;;
			*-luna*)
				vendor=omron
				;;
			*-genix*)
				vendor=ns
				;;
			*-clix*)
				vendor=intergraph
				;;
			*-mvs* | *-opened*)
				vendor=ibm
				;;
			*-os400*)
				vendor=ibm
				;;
			s390-* | s390x-*)
				vendor=ibm
				;;
			*-ptx*)
				vendor=sequent
				;;
			*-tpf*)
				vendor=ibm
				;;
			*-vxsim* | *-vxworks* | *-windiss*)
				vendor=wrs
				;;
			*-aux*)
				vendor=apple
				;;
			*-hms*)
				vendor=hitachi
				;;
			*-mpw* | *-macos*)
				vendor=apple
				;;
			*-*mint | *-mint[0-9]* | *-*MiNT | *-MiNT[0-9]*)
				vendor=atari
				;;
			*-vos*)
				vendor=stratus
				;;
		esac
		;;
esac

echo "$cpu-$vendor-${kernel:+$kernel-}$os"
exit

# Local variables:
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "timestamp='"
# time-stamp-format: "%:y-%02m-%02d"
# time-stamp-end: "'"
# End:

Deleted autosetup/autosetup-find-tclsh.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15















-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
#!/bin/sh
# Looks for a suitable tclsh or jimsh in the PATH
# If not found, builds a bootstrap jimsh in current dir from source
# Prefer $autosetup_tclsh if is set in the environment (unless ./jimsh0 works)
d="`dirname "$0"`"
for tclsh in ./jimsh0 $autosetup_tclsh jimsh tclsh tclsh8.5 tclsh8.6 tclsh8.7; do
	{ $tclsh "$d/autosetup-test-tclsh"; } 2>/dev/null && exit 0
done
echo 1>&2 "No installed jimsh or tclsh, building local bootstrap jimsh0"
for cc in ${CC_FOR_BUILD:-cc} gcc; do
	{ $cc -o jimsh0 "$d/jimsh0.c"; } 2>/dev/null || continue
	./jimsh0 "$d/autosetup-test-tclsh" && exit 0
done
echo 1>&2 "No working C compiler found. Tried ${CC_FOR_BUILD:-cc} and gcc."
echo false

Deleted autosetup/autosetup-test-tclsh.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20




















-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# A small Tcl script to verify that the chosen
# interpreter works. Sometimes we might e.g. pick up
# an interpreter for a different arch.
# Outputs the full path to the interpreter

if {[catch {info version} version] == 0} {
	# This is Jim Tcl
	if {$version >= 0.72} {
		# Ensure that regexp works
		regexp (a.*?) a
		puts [info nameofexecutable]
		exit 0
	}
} elseif {[catch {info tclversion} version] == 0} {
	if {$version >= 8.5 && ![string match 8.5a* [info patchlevel]]} {
		puts [info nameofexecutable]
		exit 0
	}
}
exit 1

Deleted autosetup/cc-db.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15















-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# Copyright (c) 2011 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# @synopsis:
#
# The 'cc-db' module provides a knowledge-base of system idiosyncrasies.
# In general, this module can always be included.

use cc

options {}

# openbsd needs sys/types.h to detect some system headers
cc-include-needs sys/socket.h sys/types.h
cc-include-needs netinet/in.h sys/types.h

Deleted autosetup/cc-lib.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187



























































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# Copyright (c) 2011 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# @synopsis:
#
# Provides a library of common tests on top of the 'cc' module.

use cc

# @cc-check-lfs
#
# The equivalent of the 'AC_SYS_LARGEFILE' macro.
#
# defines 'HAVE_LFS' if LFS is available,
# and defines '_FILE_OFFSET_BITS=64' if necessary
#
# Returns 1 if 'LFS' is available or 0 otherwise
#
proc cc-check-lfs {} {
	cc-check-includes sys/types.h
	msg-checking "Checking if -D_FILE_OFFSET_BITS=64 is needed..."
	set lfs 1
	if {[msg-quiet cc-with {-includes sys/types.h} {cc-check-sizeof off_t}] == 8} {
		msg-result no
	} elseif {[msg-quiet cc-with {-includes sys/types.h -cflags -D_FILE_OFFSET_BITS=64} {cc-check-sizeof off_t}] == 8} {
		define _FILE_OFFSET_BITS 64
		msg-result yes
	} else {
		set lfs 0
		msg-result none
	}
	define-feature lfs $lfs
	return $lfs
}

# @cc-check-endian
#
# The equivalent of the 'AC_C_BIGENDIAN' macro.
#
# defines 'HAVE_BIG_ENDIAN' if endian is known to be big,
# or 'HAVE_LITTLE_ENDIAN' if endian is known to be little.
#
# Returns 1 if determined, or 0 if not.
#
proc cc-check-endian {} {
	cc-check-includes sys/types.h sys/param.h
	set rc 0
	msg-checking "Checking endian..."
	cc-with {-includes {sys/types.h sys/param.h}} {
		if {[cctest -code {
			#if !defined(BIG_ENDIAN) || !defined(BYTE_ORDER)
				#error unknown
			#elif BYTE_ORDER != BIG_ENDIAN
				#error little
			#endif
		}]} {
			define-feature big-endian
			msg-result "big"
			set rc 1
		} elseif {[cctest -code {
			#if !defined(LITTLE_ENDIAN) || !defined(BYTE_ORDER)
				#error unknown
			#elif BYTE_ORDER != LITTLE_ENDIAN
				#error big
			#endif
		}]} {
			define-feature little-endian
			msg-result "little"
			set rc 1
		} else {
			msg-result "unknown"
		}
	}
	return $rc
}

# @cc-check-flags flag ?...?
#
# Checks whether the given C/C++ compiler flags can be used. Defines feature
# names prefixed with 'HAVE_CFLAG' and 'HAVE_CXXFLAG' respectively, and
# appends working flags to '-cflags' and 'CFLAGS' or 'CXXFLAGS'.
proc cc-check-flags {args} {
	set result 1
	array set opts [cc-get-settings]
	switch -exact -- $opts(-lang) {
		c++ {
			set lang C++
			set prefix CXXFLAG
		}
		c {
			set lang C
			set prefix CFLAG
		}
		default {
			autosetup-error "cc-check-flags failed with unknown language: $opts(-lang)"
		}
	}
	foreach flag $args {
		msg-checking "Checking whether the $lang compiler accepts $flag..."
		if {[cctest -cflags $flag]} {
			msg-result yes
			define-feature $prefix$flag
			cc-with [list -cflags [list $flag]]
			define-append ${prefix}S $flag
		} else {
			msg-result no
			set result 0
		}
	}
	return $result
}

# @cc-check-standards ver ?...?
#
# Checks whether the C/C++ compiler accepts one of the specified '-std=$ver'
# options, and appends the first working one to '-cflags' and 'CFLAGS' or
# 'CXXFLAGS'.
proc cc-check-standards {args} {
	array set opts [cc-get-settings]
	foreach std $args {
		if {[cc-check-flags -std=$std]} {
			return $std
		}
	}
	return ""
}

# Checks whether $keyword is usable as alignof
proc cctest_alignof {keyword} {
	msg-checking "Checking for $keyword..."
	if {[cctest -code "int x = ${keyword}(char), y = ${keyword}('x');"]} then {
		msg-result ok
		define-feature $keyword
	} else {
		msg-result "not found"
	}
}

# @cc-check-c11
#
# Checks for several C11/C++11 extensions and their alternatives. Currently
# checks for '_Static_assert', '_Alignof', '__alignof__', '__alignof'.
proc cc-check-c11 {} {
	msg-checking "Checking for _Static_assert..."
	if {[cctest -code {
		_Static_assert(1, "static assertions are available");
	}]} then {
		msg-result ok
		define-feature _Static_assert
	} else {
		msg-result "not found"
	}

	cctest_alignof _Alignof
	cctest_alignof __alignof__
	cctest_alignof __alignof
}

# @cc-check-alloca
#
# The equivalent of the 'AC_FUNC_ALLOCA' macro.
#
# Checks for the existence of 'alloca'
# defines 'HAVE_ALLOCA' and returns 1 if it exists.
proc cc-check-alloca {} {
	cc-check-some-feature alloca {
		cctest -includes alloca.h -code { alloca (2 * sizeof (int)); }
	}
}

# @cc-signal-return-type
#
# The equivalent of the 'AC_TYPE_SIGNAL' macro.
#
# defines 'RETSIGTYPE' to 'int' or 'void'.
proc cc-signal-return-type {} {
	msg-checking "Checking return type of signal handlers..."
	cc-with {-includes {sys/types.h signal.h}} {
		if {[cctest -code {return *(signal (0, 0)) (0) == 1;}]} {
				set type int
		} else {
				set type void
		}
		define RETSIGTYPE $type
		msg-result $type
	}
}

Deleted autosetup/cc-shared.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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

















































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# @synopsis:
#
# The 'cc-shared' module provides support for shared libraries and shared objects.
# It defines the following variables:
#
## SH_CFLAGS         Flags to use compiling sources destined for a shared library
## SH_LDFLAGS        Flags to use linking (creating) a shared library
## SH_SOPREFIX       Prefix to use to set the soname when creating a shared library
## SH_SOFULLPATH     Set to 1 if the shared library soname should include the full install path
## SH_SOEXT          Extension for shared libs
## SH_SOEXTVER       Format for versioned shared libs - %s = version
## SHOBJ_CFLAGS      Flags to use compiling sources destined for a shared object
## SHOBJ_LDFLAGS     Flags to use linking a shared object, undefined symbols allowed
## SHOBJ_LDFLAGS_R   - as above, but all symbols must be resolved
## SH_LINKRPATH      Format for setting the rpath when linking an executable, %s = path
## SH_LINKFLAGS      Flags to use linking an executable which will load shared objects
## LD_LIBRARY_PATH   Environment variable which specifies path to shared libraries
## STRIPLIBFLAGS     Arguments to strip a dynamic library

options {}

# Defaults: gcc on unix
define SHOBJ_CFLAGS -fPIC
define SHOBJ_LDFLAGS -shared
define SH_CFLAGS -fPIC
define SH_LDFLAGS -shared
define SH_LINKFLAGS -rdynamic
define SH_LINKRPATH "-Wl,-rpath -Wl,%s"
define SH_SOEXT .so
define SH_SOEXTVER .so.%s
define SH_SOPREFIX -Wl,-soname,
define LD_LIBRARY_PATH LD_LIBRARY_PATH
define STRIPLIBFLAGS --strip-unneeded

# Note: This is a helpful reference for identifying the toolchain
#       http://sourceforge.net/apps/mediawiki/predef/index.php?title=Compilers

switch -glob -- [get-define host] {
	*-*-darwin* {
		define SHOBJ_CFLAGS "-dynamic -fno-common"
		define SHOBJ_LDFLAGS "-bundle -undefined dynamic_lookup"
		define SHOBJ_LDFLAGS_R -bundle
		define SH_CFLAGS -dynamic
		define SH_LDFLAGS -dynamiclib
		define SH_LINKFLAGS ""
		define SH_SOEXT .dylib
		define SH_SOEXTVER .%s.dylib
		define SH_SOPREFIX -Wl,-install_name,
		define SH_SOFULLPATH
		define LD_LIBRARY_PATH DYLD_LIBRARY_PATH
		define STRIPLIBFLAGS -x
	}
	*-*-ming* - *-*-cygwin - *-*-msys {
		define SHOBJ_CFLAGS ""
		define SHOBJ_LDFLAGS -shared
		define SH_CFLAGS ""
		define SH_LDFLAGS -shared
		define SH_LINKRPATH ""
		define SH_LINKFLAGS ""
		define SH_SOEXT .dll
		define SH_SOEXTVER .dll
		define SH_SOPREFIX ""
		define LD_LIBRARY_PATH PATH
	}
	sparc* {
		if {[msg-quiet cc-check-decls __SUNPRO_C]} {
			msg-result "Found sun stdio compiler"
			# sun stdio compiler
			# XXX: These haven't been fully tested.
			define SHOBJ_CFLAGS -KPIC
			define SHOBJ_LDFLAGS "-G"
			define SH_CFLAGS -KPIC
			define SH_LINKFLAGS -Wl,-export-dynamic
			define SH_SOPREFIX -Wl,-h,
		}
	}
	*-*-solaris* {
		if {[msg-quiet cc-check-decls __SUNPRO_C]} {
			msg-result "Found sun stdio compiler"
			# sun stdio compiler
			# XXX: These haven't been fully tested.
			define SHOBJ_CFLAGS -KPIC
			define SHOBJ_LDFLAGS "-G"
			define SH_CFLAGS -KPIC
			define SH_LINKFLAGS -Wl,-export-dynamic
			define SH_SOPREFIX -Wl,-h,
		}
	}
	*-*-hpux {
		# XXX: These haven't been tested
		define SHOBJ_CFLAGS "+O3 +z"
		define SHOBJ_LDFLAGS -b
		define SH_CFLAGS +z
		define SH_LINKFLAGS -Wl,+s
		define LD_LIBRARY_PATH SHLIB_PATH
	}
	*-*-haiku {
		define SHOBJ_CFLAGS ""
		define SHOBJ_LDFLAGS -shared
		define SH_CFLAGS ""
		define SH_LDFLAGS -shared
		define SH_LINKFLAGS ""
		define SH_SOPREFIX ""
		define LD_LIBRARY_PATH LIBRARY_PATH
	}
}

if {![is-defined SHOBJ_LDFLAGS_R]} {
	define SHOBJ_LDFLAGS_R [get-define SHOBJ_LDFLAGS]
}

Deleted autosetup/cc.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
671
672
673
674
675
676
677
678
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





























































































































































































































































































































































































































































































































































































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# @synopsis:
#
# The 'cc' module supports checking various 'features' of the C or C++
# compiler/linker environment. Common commands are 'cc-check-includes',
# 'cc-check-types', 'cc-check-functions', 'cc-with', 'make-config-header' and 'make-template'.
#
# The following environment variables are used if set:
#
## CC       - C compiler
## CXX      - C++ compiler
## CPP      - C preprocessor
## CCACHE   - Set to "none" to disable automatic use of ccache
## CFLAGS   - Additional C compiler flags
## CXXFLAGS - Additional C++ compiler flags
## LDFLAGS  - Additional compiler flags during linking
## LIBS     - Additional libraries to use (for all tests)
## CROSS    - Tool prefix for cross compilation
#
# The following variables are defined from the corresponding
# environment variables if set.
#
## CPPFLAGS
## LINKFLAGS
## CC_FOR_BUILD
## LD

use system

options {}

# Checks for the existence of the given function by linking
#
proc cctest_function {function} {
	cctest -link 1 -declare "extern void $function\(void);" -code "$function\();"
}

# Checks for the existence of the given type by compiling
proc cctest_type {type} {
	cctest -code "$type _x;"
}

# Checks for the existence of the given type/structure member.
# e.g. "struct stat.st_mtime"
proc cctest_member {struct_member} {
	# split at the first dot
	regexp {^([^.]+)[.](.*)$} $struct_member -> struct member
	cctest -code "static $struct _s; return sizeof(_s.$member);"
}

# Checks for the existence of the given define by compiling
#
proc cctest_define {name} {
	cctest -code "#ifndef $name\n#error not defined\n#endif"
}

# Checks for the existence of the given name either as
# a macro (#define) or an rvalue (such as an enum)
#
proc cctest_decl {name} {
	cctest -code "#ifndef $name\n(void)$name;\n#endif"
}

# @cc-check-sizeof type ...
#
# Checks the size of the given types (between 1 and 32, inclusive).
# Defines a variable with the size determined, or 'unknown' otherwise.
# e.g. for type 'long long', defines 'SIZEOF_LONG_LONG'.
# Returns the size of the last type.
#
proc cc-check-sizeof {args} {
	foreach type $args {
		msg-checking "Checking for sizeof $type..."
		set size unknown
		# Try the most common sizes first
		foreach i {4 8 1 2 16 32} {
			if {[cctest -code "static int _x\[sizeof($type) == $i ? 1 : -1\] = { 1 };"]} {
				set size $i
				break
			}
		}
		msg-result $size
		set define [feature-define-name $type SIZEOF_]
		define $define $size
	}
	# Return the last result
	get-define $define
}

# Checks for each feature in $list by using the given script.
#
# When the script is evaluated, $each is set to the feature
# being checked, and $extra is set to any additional cctest args.
#
# Returns 1 if all features were found, or 0 otherwise.
proc cc-check-some-feature {list script} {
	set ret 1
	foreach each $list {
		if {![check-feature $each $script]} {
			set ret 0
		}
	}
	return $ret
}

# @cc-check-includes includes ...
#
# Checks that the given include files can be used.
proc cc-check-includes {args} {
	cc-check-some-feature $args {
		set with {}
		if {[dict exists $::autosetup(cc-include-deps) $each]} {
			set deps [dict keys [dict get $::autosetup(cc-include-deps) $each]]
			msg-quiet cc-check-includes {*}$deps
			foreach i $deps {
				if {[have-feature $i]} {
					lappend with $i
				}
			}
		}
		if {[llength $with]} {
			cc-with [list -includes $with] {
				cctest -includes $each
			}
		} else {
			cctest -includes $each
		}
	}
}

# @cc-include-needs include required ...
#
# Ensures that when checking for '$include', a check is first
# made for each '$required' file, and if found, it is included with '#include'.
proc cc-include-needs {file args} {
	foreach depfile $args {
		dict set ::autosetup(cc-include-deps) $file $depfile 1
	}
}

# @cc-check-types type ...
#
# Checks that the types exist.
proc cc-check-types {args} {
	cc-check-some-feature $args {
		cctest_type $each
	}
}

# @cc-check-defines define ...
#
# Checks that the given preprocessor symbols are defined.
proc cc-check-defines {args} {
	cc-check-some-feature $args {
		cctest_define $each
	}
}

# @cc-check-decls name ...
#
# Checks that each given name is either a preprocessor symbol or rvalue
# such as an enum. Note that the define used is 'HAVE_DECL_xxx'
# rather than 'HAVE_xxx'.
proc cc-check-decls {args} {
	set ret 1
	foreach name $args {
		msg-checking "Checking for $name..."
		set r [cctest_decl $name]
		define-feature "decl $name" $r
		if {$r} {
			msg-result "ok"
		} else {
			msg-result "not found"
			set ret 0
		}
	}
	return $ret
}

# @cc-check-functions function ...
#
# Checks that the given functions exist (can be linked).
proc cc-check-functions {args} {
	cc-check-some-feature $args {
		cctest_function $each
	}
}

# @cc-check-members type.member ...
#
# Checks that the given type/structure members exist.
# A structure member is of the form 'struct stat.st_mtime'.
proc cc-check-members {args} {
	cc-check-some-feature $args {
		cctest_member $each
	}
}

# @cc-check-function-in-lib function libs ?otherlibs?
#
# Checks that the given function can be found in one of the libs.
#
# First checks for no library required, then checks each of the libraries
# in turn.
#
# If the function is found, the feature is defined and 'lib_$function' is defined
# to '-l$lib' where the function was found, or "" if no library required.
# In addition, '-l$lib' is prepended to the 'LIBS' define.
#
# If additional libraries may be needed for linking, they should be specified
# with '$extralibs' as '-lotherlib1 -lotherlib2'.
# These libraries are not automatically added to 'LIBS'.
#
# Returns 1 if found or 0 if not.
#
proc cc-check-function-in-lib {function libs {otherlibs {}}} {
	msg-checking "Checking libs for $function..."
	set found 0
	cc-with [list -libs $otherlibs] {
		if {[cctest_function $function]} {
			msg-result "none needed"
			define lib_$function ""
			incr found
		} else {
			foreach lib $libs {
				cc-with [list -libs -l$lib] {
					if {[cctest_function $function]} {
						msg-result -l$lib
						define lib_$function -l$lib
						# prepend to LIBS
						define LIBS "-l$lib [get-define LIBS]"
						incr found
						break
					}
				}
			}
		}
	}
	define-feature $function $found
	if {!$found} {
		msg-result "no"
	}
	return $found
}

# @cc-check-tools tool ...
#
# Checks for existence of the given compiler tools, taking
# into account any cross compilation prefix.
#
# For example, when checking for 'ar', first 'AR' is checked on the command
# line and then in the environment. If not found, '${host}-ar' or
# simply 'ar' is assumed depending upon whether cross compiling.
# The path is searched for this executable, and if found 'AR' is defined
# to the executable name.
# Note that even when cross compiling, the simple 'ar' is used as a fallback,
# but a warning is generated. This is necessary for some toolchains.
#
# It is an error if the executable is not found.
#
proc cc-check-tools {args} {
	foreach tool $args {
		set TOOL [string toupper $tool]
		set exe [get-env $TOOL [get-define cross]$tool]
		if {[find-executable {*}$exe]} {
			define $TOOL $exe
			continue
		}
		if {[find-executable {*}$tool]} {
			msg-result "Warning: Failed to find $exe, falling back to $tool which may be incorrect"
			define $TOOL $tool
			continue
		}
		user-error "Failed to find $exe"
	}
}

# @cc-check-progs prog ...
#
# Checks for existence of the given executables on the path.
#
# For example, when checking for 'grep', the path is searched for
# the executable, 'grep', and if found 'GREP' is defined as 'grep'.
#
# If the executable is not found, the variable is defined as 'false'.
# Returns 1 if all programs were found, or 0 otherwise.
#
proc cc-check-progs {args} {
	set failed 0
	foreach prog $args {
		set PROG [string toupper $prog]
		msg-checking "Checking for $prog..."
		if {![find-executable $prog]} {
			msg-result no
			define $PROG false
			incr failed
		} else {
			msg-result ok
			define $PROG $prog
		}
	}
	expr {!$failed}
}

# @cc-path-progs prog ...
#
# Like cc-check-progs, but sets the define to the full path rather
# than just the program name.
#
proc cc-path-progs {args} {
	set failed 0
	foreach prog $args {
		set PROG [string toupper $prog]
		msg-checking "Checking for $prog..."
		set path [find-executable-path $prog]
		if {$path eq ""} {
			msg-result no
			define $PROG false
			incr failed
		} else {
			msg-result $path
			define $PROG $path
		}
	}
	expr {!$failed}
}

# Adds the given settings to $::autosetup(ccsettings) and
# returns the old settings.
#
proc cc-add-settings {settings} {
	if {[llength $settings] % 2} {
		autosetup-error "settings list is missing a value: $settings"
	}

	set prev [cc-get-settings]
	# workaround a bug in some versions of jimsh by forcing
	# conversion of $prev to a list
	llength $prev

	array set new $prev

	foreach {name value} $settings {
		switch -exact -- $name {
			-cflags - -includes {
				# These are given as lists
				lappend new($name) {*}[list-non-empty $value]
			}
			-declare {
				lappend new($name) $value
			}
			-libs {
				# Note that new libraries are added before previous libraries
				set new($name) [list {*}[list-non-empty $value] {*}$new($name)]
			}
			-link - -lang - -nooutput {
				set new($name) $value
			}
			-source - -sourcefile - -code {
				# XXX: These probably are only valid directly from cctest
				set new($name) $value
			}
			default {
				autosetup-error "unknown cctest setting: $name"
			}
		}
	}

	cc-store-settings [array get new]

	return $prev
}

proc cc-store-settings {new} {
	set ::autosetup(ccsettings) $new
}

proc cc-get-settings {} {
	return $::autosetup(ccsettings)
}

# Similar to cc-add-settings, but each given setting
# simply replaces the existing value.
#
# Returns the previous settings
proc cc-update-settings {args} {
	set prev [cc-get-settings]
	cc-store-settings [dict merge $prev $args]
	return $prev
}

# @cc-with settings ?{ script }?
#
# Sets the given 'cctest' settings and then runs the tests in '$script'.
# Note that settings such as '-lang' replace the current setting, while
# those such as '-includes' are appended to the existing setting.
#
# If no script is given, the settings become the default for the remainder
# of the 'auto.def' file.
#
## cc-with {-lang c++} {
##   # This will check with the C++ compiler
##   cc-check-types bool
##   cc-with {-includes signal.h} {
##     # This will check with the C++ compiler, signal.h and any existing includes.
##     ...
##   }
##   # back to just the C++ compiler
## }
#
# The '-libs' setting is special in that newer values are added *before* earlier ones.
#
## cc-with {-libs {-lc -lm}} {
##   cc-with {-libs -ldl} {
##     cctest -libs -lsocket ...
##     # libs will be in this order: -lsocket -ldl -lc -lm
##   }
## }
proc cc-with {settings args} {
	if {[llength $args] == 0} {
		cc-add-settings $settings
	} elseif {[llength $args] > 1} {
		autosetup-error "usage: cc-with settings ?script?"
	} else {
		set save [cc-add-settings $settings]
		set rc [catch {uplevel 1 [lindex $args 0]} result info]
		cc-store-settings $save
		if {$rc != 0} {
			return -code [dict get $info -code] $result
		}
		return $result
	}
}

# @cctest ?settings?
#
# Low level C/C++ compiler checker. Compiles and or links a small C program
# according to the arguments and returns 1 if OK, or 0 if not.
#
# Supported settings are:
#
## -cflags cflags      A list of flags to pass to the compiler
## -includes list      A list of includes, e.g. {stdlib.h stdio.h}
## -declare code       Code to declare before main()
## -link 1             Don't just compile, link too
## -lang c|c++         Use the C (default) or C++ compiler
## -libs liblist       List of libraries to link, e.g. {-ldl -lm}
## -code code          Code to compile in the body of main()
## -source code        Compile a complete program. Ignore -includes, -declare and -code
## -sourcefile file    Shorthand for -source [readfile [get-define srcdir]/$file]
## -nooutput 1         Treat any compiler output (e.g. a warning) as an error
#
# Unless '-source' or '-sourcefile' is specified, the C program looks like:
#
## #include <firstinclude>   /* same for remaining includes in the list */
##
## declare-code              /* any code in -declare, verbatim */
##
## int main(void) {
##   code                    /* any code in -code, verbatim */
##   return 0;
## }
#
# Any failures are recorded in 'config.log'
#
proc cctest {args} {
	set tmp conftest__

	# Easiest way to merge in the settings
	cc-with $args {
		array set opts [cc-get-settings]
	}

	if {[info exists opts(-sourcefile)]} {
		set opts(-source) [readfile [get-define srcdir]/$opts(-sourcefile) "#error can't find $opts(-sourcefile)"]
	}
	if {[info exists opts(-source)]} {
		set lines $opts(-source)
	} else {
		foreach i $opts(-includes) {
			if {$opts(-code) ne "" && ![feature-checked $i]} {
				# Compiling real code with an unchecked header file
				# Quickly (and silently) check for it now

				# Remove all -includes from settings before checking
				set saveopts [cc-update-settings -includes {}]
				msg-quiet cc-check-includes $i
				cc-store-settings $saveopts
			}
			if {$opts(-code) eq "" || [have-feature $i]} {
				lappend source "#include <$i>"
			}
		}
		lappend source {*}$opts(-declare)
		lappend source "int main(void) {"
		lappend source $opts(-code)
		lappend source "return 0;"
		lappend source "}"

		set lines [join $source \n]
	}

	# Build the command line
	set cmdline {}
	lappend cmdline {*}[get-define CCACHE]
	switch -exact -- $opts(-lang) {
		c++ {
			set src conftest__.cpp
			lappend cmdline {*}[get-define CXX] {*}[get-define CXXFLAGS]
		}
		c {
			set src conftest__.c
			lappend cmdline {*}[get-define CC] {*}[get-define CFLAGS]
		}
		default {
			autosetup-error "cctest called with unknown language: $opts(-lang)"
		}
	}

	if {$opts(-link)} {
		lappend cmdline {*}[get-define LDFLAGS]
	} else {
		set tmp conftest__.o
		lappend cmdline -c
	}
	lappend cmdline {*}$opts(-cflags) {*}[get-define cc-default-debug ""]
	lappend cmdline $src -o $tmp {*}$opts(-libs)
	if {$opts(-link)} {
		lappend cmdline {*}[get-define LIBS]
	}

	# At this point we have the complete command line and the
	# complete source to be compiled. Get the result from cache if
	# we can
	if {[info exists ::cc_cache($cmdline,$lines)]} {
		msg-checking "(cached) "
		set ok $::cc_cache($cmdline,$lines)
		if {$::autosetup(debug)} {
			configlog "From cache (ok=$ok): [join $cmdline]"
			configlog "============"
			configlog $lines
			configlog "============"
		}
		return $ok
	}

	writefile $src $lines\n

	set ok 1
	set err [catch {exec-with-stderr {*}$cmdline} result errinfo]
	if {$err || ($opts(-nooutput) && [string length $result])} {
		configlog "Failed: [join $cmdline]"
		configlog $result
		configlog "============"
		configlog "The failed code was:"
		configlog $lines
		configlog "============"
		set ok 0
	} elseif {$::autosetup(debug)} {
		configlog "Compiled OK: [join $cmdline]"
		configlog "============"
		configlog $lines
		configlog "============"
	}
	file delete $src
	file delete $tmp

	# cache it
	set ::cc_cache($cmdline,$lines) $ok

	return $ok
}

# @make-autoconf-h outfile ?auto-patterns=HAVE_*? ?bare-patterns=SIZEOF_*?
#
# Deprecated - see 'make-config-header'
proc make-autoconf-h {file {autopatterns {HAVE_*}} {barepatterns {SIZEOF_* HAVE_DECL_*}}} {
	user-notice "*** make-autoconf-h is deprecated -- use make-config-header instead"
	make-config-header $file -auto $autopatterns -bare $barepatterns
}

# @make-config-header outfile ?-auto patternlist? ?-bare patternlist? ?-none patternlist? ?-str patternlist? ...
#
# Examines all defined variables which match the given patterns
# and writes an include file, '$file', which defines each of these.
# Variables which match '-auto' are output as follows:
# - defines which have the value '0' are ignored.
# - defines which have integer values are defined as the integer value.
# - any other value is defined as a string, e.g. '"value"'
# Variables which match '-bare' are defined as-is.
# Variables which match '-str' are defined as a string, e.g. '"value"'
# Variables which match '-none' are omitted.
#
# Note that order is important. The first pattern that matches is selected.
# Default behaviour is:
#
##  -bare {SIZEOF_* HAVE_DECL_*} -auto HAVE_* -none *
#
# If the file would be unchanged, it is not written.
proc make-config-header {file args} {
	set guard _[string toupper [regsub -all {[^a-zA-Z0-9]} [file tail $file] _]]
	file mkdir [file dirname $file]
	set lines {}
	lappend lines "#ifndef $guard"
	lappend lines "#define $guard"

	# Add some defaults
	lappend args -bare {SIZEOF_* HAVE_DECL_*} -auto HAVE_*

	foreach n [lsort [dict keys [all-defines]]] {
		set value [get-define $n]
		set type [calc-define-output-type $n $args]
		switch -exact -- $type {
			-bare {
				# Just output the value unchanged
			}
			-none {
				continue
			}
			-str {
				set value \"[string map [list \\ \\\\ \" \\\"] $value]\"
			}
			-auto {
				# Automatically determine the type
				if {$value eq "0"} {
					lappend lines "/* #undef $n */"
					continue
				}
				if {![string is integer -strict $value]} {
					set value \"[string map [list \\ \\\\ \" \\\"] $value]\"
				}
			}
			"" {
				continue
			}
			default {
				autosetup-error "Unknown type in make-config-header: $type"
			}
		}
		lappend lines "#define $n $value"
	}
	lappend lines "#endif"
	set buf [join $lines \n]
	write-if-changed $file $buf {
		msg-result "Created $file"
	}
}

proc calc-define-output-type {name spec} {
	foreach {type patterns} $spec {
		foreach pattern $patterns {
			if {[string match $pattern $name]} {
				return $type
			}
		}
	}
	return ""
}

# Initialise some values from the environment or commandline or default settings
foreach i {LDFLAGS LIBS CPPFLAGS LINKFLAGS {CFLAGS "-g -O2"}} {
	lassign $i var default
	define $var [get-env $var $default]
}

if {[env-is-set CC]} {
	# Set by the user, so don't try anything else
	set try [list [get-env CC ""]]
} else {
	# Try some reasonable options
	set try [list [get-define cross]cc [get-define cross]gcc]
}
define CC [find-an-executable {*}$try]
if {[get-define CC] eq ""} {
	user-error "Could not find a C compiler. Tried: [join $try ", "]"
}

define CPP [get-env CPP "[get-define CC] -E"]

# XXX: Could avoid looking for a C++ compiler until requested
# If CXX isn't found, it is set to the empty string.
if {[env-is-set CXX]} {
	define CXX [find-an-executable -required [get-env CXX ""]]
} else {
	define CXX [find-an-executable [get-define cross]c++ [get-define cross]g++]
}

# CXXFLAGS default to CFLAGS if not specified
define CXXFLAGS [get-env CXXFLAGS [get-define CFLAGS]]

# May need a CC_FOR_BUILD, so look for one
define CC_FOR_BUILD [find-an-executable [get-env CC_FOR_BUILD ""] cc gcc false]

if {[get-define CC] eq ""} {
	user-error "Could not find a C compiler. Tried: [join $try ", "]"
}

define CCACHE [find-an-executable [get-env CCACHE ccache]]

# If any of these are set in the environment, propagate them to the AUTOREMAKE commandline
foreach i {CC CXX CCACHE CPP CFLAGS CXXFLAGS CXXFLAGS LDFLAGS LIBS CROSS CPPFLAGS LINKFLAGS CC_FOR_BUILD LD} {
	if {[env-is-set $i]} {
		# Note: If the variable is set on the command line, get-env will return that value
		# so the command line will continue to override the environment
		define-append AUTOREMAKE [quote-if-needed $i=[get-env $i ""]]
	}
}

# Initial cctest settings
cc-store-settings {-cflags {} -includes {} -declare {} -link 0 -lang c -libs {} -code {} -nooutput 0}
set autosetup(cc-include-deps) {}

msg-result "C compiler...[get-define CCACHE] [get-define CC] [get-define CFLAGS]"
if {[get-define CXX] ne "false"} {
	msg-result "C++ compiler...[get-define CCACHE] [get-define CXX] [get-define CXXFLAGS]"
}
msg-result "Build C compiler...[get-define CC_FOR_BUILD]"

# On Darwin, we prefer to use -g0 to avoid creating .dSYM directories
# but some compilers may not support it, so test here.
switch -glob -- [get-define host] {
	*-*-darwin* {
		if {[cctest -cflags {-g0}]} {
			define cc-default-debug -g0
		}
	}
}

if {![cc-check-includes stdlib.h]} {
	user-error "Compiler does not work. See config.log"
}

Deleted autosetup/default.auto.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

























-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# Copyright (c) 2012 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Auto-load module for 'make' build system integration

use init

autosetup_add_init_type make {Simple "make" build system} {
	autosetup_check_create auto.def \
{# Initial auto.def created by 'autosetup --init=make'

use cc

# Add any user options here
options {
}

make-config-header config.h
make-template Makefile.in
}

	if {![file exists Makefile.in]} {
		puts "Note: I don't see Makefile.in. You will probably need to create one."
	}
}

Deleted autosetup/jimsh0.c.

more than 10,000 changes

Deleted autosetup/local.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# For this project, disable the pager for --help and --ref
# The user can still enable by using --nopager=0 or --disable-nopager
dict set autosetup(optdefault) nopager 1

# Searches for a usable Tcl (prefer 8.6, 8.5, 8.4) in the given paths
# Returns a dictionary of the contents of the tclConfig.sh file, or
# empty if not found
proc parse-tclconfig-sh {args} {
	foreach p $args {
		# Allow pointing directly to the path containing tclConfig.sh
		if {[file exists $p/tclConfig.sh]} {
			return [parse-tclconfig-sh-file $p/tclConfig.sh]
		}
		# Some systems allow for multiple versions
		foreach libpath {lib/tcl8.6 lib/tcl8.5 lib/tcl8.4 lib/tcl tcl lib}  {
			if {[file exists $p/$libpath/tclConfig.sh]} {
				return [parse-tclconfig-sh-file $p/$libpath/tclConfig.sh]
			}
		}
	}
}

proc parse-tclconfig-sh-file {filename} {
	foreach line [split [readfile $filename] \n] {
		if {[regexp {^(TCL_[^=]*)=(.*)$} $line -> name value]} {
			set value [regsub -all {\$\{.*\}} $value ""]
			set tclconfig($name) [string trim $value ']
		}
	}
	return [array get tclconfig]
}

Deleted autosetup/pkg-config.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168








































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# Copyright (c) 2016 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# @synopsis:
#
# The 'pkg-config' module allows package information to be found via 'pkg-config'.
#
# If not cross-compiling, the package path should be determined automatically
# by 'pkg-config'.
# If cross-compiling, the default package path is the compiler sysroot.
# If the C compiler doesn't support '-print-sysroot', the path can be supplied
# by the '--sysroot' option or by defining 'SYSROOT'.
#
# 'PKG_CONFIG' may be set to use an alternative to 'pkg-config'.

use cc

options {
	sysroot:dir => "Override compiler sysroot for pkg-config search path"
}

# @pkg-config-init ?required?
#
# Initialises the 'pkg-config' system. Unless '$required' is set to 0,
# it is a fatal error if a usable 'pkg-config' is not found .
#
# This command will normally be called automatically as required,
# but it may be invoked explicitly if lack of 'pkg-config' is acceptable.
#
# Returns 1 if ok, or 0 if 'pkg-config' not found/usable (only if '$required' is 0).
#
proc pkg-config-init {{required 1}} {
	if {[is-defined HAVE_PKG_CONFIG]} {
		return [get-define HAVE_PKG_CONFIG]
	}
	set found 0

	define PKG_CONFIG [get-env PKG_CONFIG pkg-config]
	msg-checking "Checking for pkg-config..."

	if {[catch {exec [get-define PKG_CONFIG] --version} version]} {
		msg-result "[get-define PKG_CONFIG] (not found)"
		if {$required} {
			user-error "No usable pkg-config"
		}
	} else {
		msg-result $version
		define PKG_CONFIG_VERSION $version

		set found 1

		if {[opt-str sysroot o]} {
			define SYSROOT [file-normalize $o]
			msg-result "Using specified sysroot [get-define SYSROOT]"
		} elseif {[get-define build] ne [get-define host]} {
			if {[catch {exec-with-stderr {*}[get-define CC] -print-sysroot} result errinfo] == 0} {
				# Use the compiler sysroot, if there is one
				define SYSROOT $result
				msg-result "Found compiler sysroot $result"
			} else {
				configlog "[get-define CC] -print-sysroot: $result"
				set msg "pkg-config: Cross compiling, but no compiler sysroot and no --sysroot supplied"
				if {$required} {
					user-error $msg
				} else {
					msg-result $msg
				}
				set found 0
			}
		}
		if {[is-defined SYSROOT]} {
			set sysroot [get-define SYSROOT]

			# XXX: It's possible that these should be set only when invoking pkg-config
			global env
			set env(PKG_CONFIG_DIR) ""
			# Supposedly setting PKG_CONFIG_LIBDIR means that PKG_CONFIG_PATH is ignored,
			# but it doesn't seem to work that way in practice
			set env(PKG_CONFIG_PATH) ""
			# Do we need to try /usr/local as well or instead?
			set env(PKG_CONFIG_LIBDIR) $sysroot/usr/lib/pkgconfig:$sysroot/usr/share/pkgconfig
			set env(PKG_CONFIG_SYSROOT_DIR) $sysroot
		}
	}
	define HAVE_PKG_CONFIG $found
	return $found
}

# @pkg-config module ?requirements?
#
# Use 'pkg-config' to find the given module meeting the given requirements.
# e.g.
#
## pkg-config pango >= 1.37.0
#
# If found, returns 1 and sets 'HAVE_PKG_PANGO' to 1 along with:
#
## PKG_PANGO_VERSION to the found version
## PKG_PANGO_LIBS    to the required libs (--libs-only-l)
## PKG_PANGO_LDFLAGS to the required linker flags (--libs-only-L)
## PKG_PANGO_CFLAGS  to the required compiler flags (--cflags)
#
# If not found, returns 0.
#
proc pkg-config {module args} {
	set ok [pkg-config-init]

	msg-checking "Checking for $module $args..."

	if {!$ok} {
		msg-result "no pkg-config"
		return 0
	}

	set pkgconfig [get-define PKG_CONFIG]

	set ret [catch {exec $pkgconfig --modversion "$module $args"} version]
	configlog "$pkgconfig --modversion $module $args: $version"
	if {$ret} {
		msg-result "not found"
		return 0
	}
	# Sometimes --modversion succeeds but because of dependencies it isn't usable
	# This seems to show up with --cflags
	set ret [catch {exec $pkgconfig --cflags $module} cflags]
	if {$ret} {
		msg-result "unusable ($version - see config.log)"
		configlog "$pkgconfig --cflags $module"
		configlog $cflags
		return 0
	}
	msg-result $version
	set prefix [feature-define-name $module PKG_]
	define HAVE_${prefix}
	define ${prefix}_VERSION $version
	define ${prefix}_CFLAGS $cflags
	define ${prefix}_LIBS [exec $pkgconfig --libs-only-l $module]
	define ${prefix}_LDFLAGS [exec $pkgconfig --libs-only-L $module]
	return 1
}

# @pkg-config-get module setting
#
# Convenience access to the results of 'pkg-config'.
#
# For example, '[pkg-config-get pango CFLAGS]' returns
# the value of 'PKG_PANGO_CFLAGS', or '""' if not defined.
proc pkg-config-get {module name} {
	set prefix [feature-define-name $module PKG_]
	get-define ${prefix}_${name} ""
}

# @pkg-config-get-var module variable
#
# Return the value of the given variable from the given pkg-config module.
# The module must already have been successfully detected with pkg-config.
# e.g.
#
## if {[pkg-config harfbuzz >= 2.5]} {
##   define harfbuzz_libdir [pkg-config-get-var harfbuzz libdir]
## }
#
# Returns the empty string if the variable isn't defined.
proc pkg-config-get-var {module variable} {
	set pkgconfig [get-define PKG_CONFIG]
	set prefix [feature-define-name $module HAVE_PKG_]
	exec $pkgconfig $module --variable $variable
}

Deleted autosetup/system.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407























































































































































































































































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# @synopsis:
#
# This module supports common system interrogation and options
# such as '--host', '--build', '--prefix', and setting 'srcdir', 'builddir', and 'EXEEXT'.
#
# It also support the "feature" naming convention, where searching
# for a feature such as 'sys/type.h' defines 'HAVE_SYS_TYPES_H'.
#
# It defines the following variables, based on '--prefix' unless overridden by the user:
#
## datadir
## sysconfdir
## sharedstatedir
## localstatedir
## infodir
## mandir
## includedir
#
# If '--prefix' is not supplied, it defaults to '/usr/local' unless 'defaultprefix' is defined *before*
# including the 'system' module.

if {[is-defined defaultprefix]} {
	user-notice "Note: defaultprefix is deprecated. Use options-defaults to set default options"
	options-defaults [list prefix [get-define defaultprefix]]
}

options {
	host:host-alias =>		{a complete or partial cpu-vendor-opsys for the system where
							the application will run (defaults to the same value as --build)}
	build:build-alias =>	{a complete or partial cpu-vendor-opsys for the system
							where the application will be built (defaults to the
							result of running config.guess)}
	prefix:dir=/usr/local => {the target directory for the build (default: '@default@')}

	# These (hidden) options are supported for autoconf/automake compatibility
	exec-prefix:
	bindir:
	sbindir:
	includedir:
	mandir:
	infodir:
	libexecdir:
	datadir:
	libdir:
	sysconfdir:
	sharedstatedir:
	localstatedir:
	runstatedir:
	maintainer-mode=0
	dependency-tracking=0
	silent-rules=0
}

# @check-feature name { script }
#
# defines feature '$name' to the return value of '$script',
# which should be 1 if found or 0 if not found.
#
# e.g. the following will define 'HAVE_CONST' to 0 or 1.
#
## check-feature const {
##     cctest -code {const int _x = 0;}
## }
proc check-feature {name code} {
	msg-checking "Checking for $name..."
	set r [uplevel 1 $code]
	define-feature $name $r
	if {$r} {
		msg-result "ok"
	} else {
		msg-result "not found"
	}
	return $r
}

# @have-feature name ?default=0?
#
# Returns the value of feature '$name' if defined, or '$default' if not.
#
# See 'feature-define-name' for how the "feature" name
# is translated into the "define" name.
#
proc have-feature {name {default 0}} {
	get-define [feature-define-name $name] $default
}

# @define-feature name ?value=1?
#
# Sets the feature 'define' to '$value'.
#
# See 'feature-define-name' for how the "feature" name
# is translated into the "define" name.
#
proc define-feature {name {value 1}} {
	define [feature-define-name $name] $value
}

# @feature-checked name
#
# Returns 1 if feature '$name' has been checked, whether true or not.
#
proc feature-checked {name} {
	is-defined [feature-define-name $name]
}

# @feature-define-name name ?prefix=HAVE_?
#
# Converts a "feature" name to the corresponding "define",
# e.g. 'sys/stat.h' becomes 'HAVE_SYS_STAT_H'.
#
# Converts '*' to 'P' and all non-alphanumeric to underscore.
#
proc feature-define-name {name {prefix HAVE_}} {
	string toupper $prefix[regsub -all {[^a-zA-Z0-9]} [regsub -all {[*]} $name p] _]
}

# @write-if-changed filename contents ?script?
#
# If '$filename' doesn't exist, or it's contents are different to '$contents',
# the file is written and '$script' is evaluated.
#
# Otherwise a "file is unchanged" message is displayed.
proc write-if-changed {file buf {script {}}} {
	set old [readfile $file ""]
	if {$old eq $buf && [file exists $file]} {
		msg-result "$file is unchanged"
	} else {
		writefile $file $buf\n
		uplevel 1 $script
	}
}


# @include-file infile mapping
#
# The core of make-template, called recursively for each @include
# directive found within that template so that this proc's result
# is the fully-expanded template.
#
# The mapping parameter is how we expand @varname@ within the template.
# We do that inline within this step only for @include directives which
# can have variables in the filename arg.  A separate substitution pass
# happens when this recursive function returns, expanding the rest of
# the variables.
#
proc include-file {infile mapping} {
	# A stack of true/false conditions, one for each nested conditional
	# starting with "true"
	set condstack {1}
	set result {}
	set linenum 0
	foreach line [split [readfile $infile] \n] {
		incr linenum
		if {[regexp {^@(if|else|endif)(\s*)(.*)} $line -> condtype condspace condargs]} {
			if {$condtype eq "if"} {
				if {[string length $condspace] == 0} {
					autosetup-error "$infile:$linenum: Invalid expression: $line"
				}
				if {[llength $condargs] == 1} {
					# ABC => [get-define ABC] ni {0 ""}
					# !ABC => [get-define ABC] in {0 ""}
					lassign $condargs condvar
					if {[regexp {^!(.*)} $condvar -> condvar]} {
						set op in
					} else {
						set op ni
					}
					set condexpr "\[[list get-define $condvar]\] $op {0 {}}"
				} else {
					# Translate alphanumeric ABC into [get-define ABC] and leave the
					# rest of the expression untouched
					regsub -all {([A-Z][[:alnum:]_]*)} $condargs {[get-define \1]} condexpr
				}
				if {[catch [list expr $condexpr] condval]} {
					dputs $condval
					autosetup-error "$infile:$linenum: Invalid expression: $line"
				}
				dputs "@$condtype: $condexpr => $condval"
			}
			if {$condtype ne "if"} {
				if {[llength $condstack] <= 1} {
					autosetup-error "$infile:$linenum: Error: @$condtype missing @if"
				} elseif {[string length $condargs] && [string index $condargs 0] ne "#"} {
					autosetup-error "$infile:$linenum: Error: Extra arguments after @$condtype"
				}
			}
			switch -exact $condtype {
				if {
					# push condval
					lappend condstack $condval
				}
				else {
					# Toggle the last entry
					set condval [lpop condstack]
					set condval [expr {!$condval}]
					lappend condstack $condval
				}
				endif {
					if {[llength $condstack] == 0} {
						user-notice "$infile:$linenum: Error: @endif missing @if"
					}
					lpop condstack
				}
			}
			continue
		} elseif {[regexp {^@include\s+(.*)} $line -> filearg]} {
			set incfile [string map $mapping $filearg]
			if {[file exists $incfile]} {
				lappend ::autosetup(deps) [file-normalize $incfile]
				lappend result {*}[include-file $incfile $mapping]
			} else {
				user-error "$infile:$linenum: Include file $incfile is missing"
			}
			continue
		} elseif {[regexp {^@define\s+(\w+)\s+(.*)} $line -> var val]} {
			define $var $val
			continue
		}
		# Only output this line if the stack contains all "true"
		if {"0" in $condstack} {
			continue
		}
		lappend result $line
	}
	return $result
}


# @make-template template ?outfile?
#
# Reads the input file '<srcdir>/$template' and writes the output file '$outfile'
# (unless unchanged).
# If '$outfile' is blank/omitted, '$template' should end with '.in' which
# is removed to create the output file name.
#
# Each pattern of the form '@define@' is replaced with the corresponding
# "define", if it exists, or left unchanged if not.
#
# The special value '@srcdir@' is substituted with the relative
# path to the source directory from the directory where the output
# file is created, while the special value '@top_srcdir@' is substituted
# with the relative path to the top level source directory.
#
# Conditional sections may be specified as follows:
## @if NAME eq "value"
## lines
## @else
## lines
## @endif
#
# Where 'NAME' is a defined variable name and '@else' is optional.
# Note that variables names *must* start with an uppercase letter.
# If the expression does not match, all lines through '@endif' are ignored.
#
# The alternative forms may also be used:
## @if NAME  (true if the variable is defined, but not empty and not "0")
## @if !NAME  (opposite of the form above)
## @if <general-tcl-expression>
#
# In the general Tcl expression, any words beginning with an uppercase letter
# are translated into [get-define NAME]
#
# Expressions may be nested
#
proc make-template {template {out {}}} {
	set infile [file join $::autosetup(srcdir) $template]

	if {![file exists $infile]} {
		user-error "Template $template is missing"
	}

	# Define this as late as possible
	define AUTODEPS $::autosetup(deps)

	if {$out eq ""} {
		if {[file ext $template] ne ".in"} {
			autosetup-error "make_template $template has no target file and can't guess"
		}
		set out [file rootname $template]
	}

	set outdir [file dirname $out]

	# Make sure the directory exists
	file mkdir $outdir

	# Set up srcdir and top_srcdir to be relative to the target dir
	define srcdir [relative-path [file join $::autosetup(srcdir) $outdir] $outdir]
	define top_srcdir [relative-path $::autosetup(srcdir) $outdir]

	# Build map from global defines to their values so they can be
	# substituted into @include file names.
	proc build-define-mapping {} {
		set mapping {}
		foreach {n v} [array get ::define] {
			lappend mapping @$n@ $v
		}
		return $mapping
	}
	set mapping [build-define-mapping]

	set result [include-file $infile $mapping]

	# Rebuild the define mapping in case we ran across @define
	# directives in the template or a file it @included, then
	# apply that mapping to the expanded template.
	set mapping [build-define-mapping]
	write-if-changed $out [string map $mapping [join $result \n]] {
		msg-result "Created [relative-path $out] from [relative-path $template]"
	}
}

# build/host tuples and cross-compilation prefix
opt-str build build ""
define build_alias $build
if {$build eq ""} {
	define build [config_guess]
} else {
	define build [config_sub $build]
}

opt-str host host ""
define host_alias $host
if {$host eq ""} {
	define host [get-define build]
	set cross ""
} else {
	define host [config_sub $host]
	set cross $host-
}
define cross [get-env CROSS $cross]

# build/host _cpu, _vendor and _os
foreach type {build host} {
	set v [get-define $type]
	if {![regexp {^([^-]+)-([^-]+)-(.*)$} $v -> cpu vendor os]} {
		user-error "Invalid canonical $type: $v"
	}
	define ${type}_cpu $cpu
	define ${type}_vendor $vendor
	define ${type}_os $os
}

opt-str prefix prefix /usr/local

# These are for compatibility with autoconf
define target [get-define host]
define prefix $prefix
define builddir $autosetup(builddir)
define srcdir $autosetup(srcdir)
define top_srcdir $autosetup(srcdir)
define abs_top_srcdir [file-normalize $autosetup(srcdir)]
define abs_top_builddir [file-normalize $autosetup(builddir)]

# autoconf supports all of these
define exec_prefix [opt-str exec-prefix exec_prefix $prefix]
foreach {name defpath} {
	bindir /bin
	sbindir /sbin
	libexecdir /libexec
	libdir /lib
} {
	define $name [opt-str $name o $exec_prefix$defpath]
}
foreach {name defpath} {
	datadir /share
	sharedstatedir /com
	infodir /share/info
	mandir /share/man
	includedir /include
} {
	define $name [opt-str $name o $prefix$defpath]
}
if {$prefix ne {/usr}} {
	opt-str sysconfdir sysconfdir $prefix/etc
} else {
	opt-str sysconfdir sysconfdir /etc
}
define sysconfdir $sysconfdir

define localstatedir [opt-str localstatedir o /var]
define runstatedir [opt-str runstatedir o /run]

define SHELL [get-env SHELL [find-an-executable sh bash ksh]]

# These could be used to generate Makefiles following some automake conventions
define AM_SILENT_RULES [opt-bool silent-rules]
define AM_MAINTAINER_MODE [opt-bool maintainer-mode]
define AM_DEPENDENCY_TRACKING [opt-bool dependency-tracking]

# Windows vs. non-Windows
switch -glob -- [get-define host] {
	*-*-ming* - *-*-cygwin - *-*-msys {
		define-feature windows
		define EXEEXT .exe
	}
	default {
		define EXEEXT ""
	}
}

# Display
msg-result "Host System...[get-define host]"
msg-result "Build System...[get-define build]"

Deleted autosetup/tmake.auto.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55























































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# Copyright (c) 2016 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# Auto-load module for 'tmake' build system integration

use init

autosetup_add_init_type tmake "Tcl-based tmake build system" {
	autosetup_check_create auto.def \
{# Initial auto.def created by 'autosetup --init=tmake'
# vim:set syntax=tcl:

use cc cc-lib cc-db cc-shared
use tmake

# Add any user options here
# Really want a --configure that takes over the rest of the command line
options {
}

cc-check-tools ar ranlib

set objdir [get-env BUILDDIR objdir]

make-config-header $objdir/include/autoconf.h
make-tmake-settings $objdir/settings.conf {[A-Z]*} *dir lib_*
}

	autosetup_check_create project.spec \
{# Initial project.spec created by 'autosetup --init=tmake'

tmake-require-version 0.7.3

# vim:set syntax=tcl:
define? DESTDIR _install

# XXX If configure creates additional/different files than include/autoconf.h
#     that should be reflected here
Autosetup include/autoconf.h

# e.g. for autoconf.h
IncludePaths include

ifconfig !CONFIGURED {
	# Not configured, so don't process subdirs
	AutoSubDirs off
	# And don't process this file any further
	ifconfig false
}
}

	if {![file exists build.spec]} {
		puts "Note: I don't see build.spec. Try running: tmake --genie"
	}
}

Deleted autosetup/tmake.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52




















































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# Copyright (c) 2011 WorkWare Systems http://www.workware.net.au/
# All rights reserved

# @synopsis:
#
# The 'tmake' module makes it easy to support the tmake build system.
#
# The following variables are set:
#
## CONFIGURED  - to indicate that the project is configured

use system

options {}

define CONFIGURED

# @make-tmake-settings outfile patterns ...
#
# Examines all defined variables which match the given patterns (defaults to '*')
# and writes a tmake-compatible .conf file defining those variables.
# For example, if 'ABC' is '"3 monkeys"' and 'ABC' matches a pattern, then the file will include:
#
## define ABC {3 monkeys}
#
# If the file would be unchanged, it is not written.
#
# Typical usage is:
#
## make-tmake-settings [get-env BUILDDIR objdir]/settings.conf {[A-Z]*}
proc make-tmake-settings {file args} {
	file mkdir [file dirname $file]
	set lines {}

	if {[llength $args] == 0} {
		set args *
	}

	foreach n [lsort [dict keys [all-defines]]] {
		foreach p $args {
			if {[string match $p $n]} {
				set value [get-define $n]
				lappend lines "define $n [list $value]"
				break
			}
		}
	}
	set buf [join $lines \n]
	write-if-changed $file $buf {
		msg-result "Created $file"
	}
}

Deleted autosetup/wh-common.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411



























































































































































































































































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
########################################################################
# Routines for Steve Bennett's autosetup which are common to trees
# managed under the umbrella of wanderinghorse.net.
#
# In the interest of assisting to keep multiple copies of this file
# up to date:s
#
# The "canonical" version is the one in libfossil:
#
#  https://fossil.wanderinghorse.net/r/libfossil/finfo?name=autosetup/wh-common.tcl
########################################################################

array set whcache {} ; # used for caching various results.

########################################################################
# wh-lshift shifts $count elements from the list named $listVar and
# returns them.
#
# Modified slightly from: https://wiki.tcl-lang.org/page/lshift
#
# On an empty list, returns "".
proc wh-lshift {listVar {count 1}} {
    upvar 1 $listVar l
    if {![info exists l]} {
        # make the error message show the real variable name
        error "can't read \"$listVar\": no such variable"
    }
    if {![llength $l]} {
        # error Empty
        return ""
    }
    set r [lrange $l 0 [incr count -1]]
    set l [lreplace $l [set l 0] $count]
    return $r
}

########################################################################
# A proxy for cc-check-function-in-lib which "undoes" any changes that
# routine makes to the LIBS define. Returns the result of
# cc-check-function-in-lib.
proc wh-check-function-in-lib {function libs {otherlibs {}}} {
    set _LIBS [get-define LIBS]
    set found [cc-check-function-in-lib $function $libs $otherlibs]
    define LIBS $_LIBS
    return $found
}

########################################################################
# Look for binary named $binName and `define`s $defName to that full
# path, or an empty string if not found. Returns the value it defines.
# This caches the result for a given $binName/$defName combination, so
# calls after the first for a given combination will always return the
# same result.
#
# If defName is empty then "BIN_X" is used, where X is the upper-case
# form of $binName with any '-' characters removed.
proc wh-bin-define {binName {defName {}}} {
    global whcache
    set cacheName "$binName:$defName"
    set check {}
    if {[info exists whcache($cacheName)]} {
        set check $whcache($cacheName)
    }
    msg-checking "Looking for $binName ... "
    if {"" ne $check} {
        set lbl $check
        if {" _ 0 _ " eq $check} {
            set lbl "not found"
            set check ""
        }
        msg-result "(cached) $lbl"
        return $check
    }
    set check [find-executable-path $binName]
    if {"" eq $check} {
        msg-result "not found"
        set whcache($cacheName) " _ 0 _ "
    } else {
        msg-result $check
        set whcache($cacheName) $check
    }
    if {"" eq $defName} {
        set defName "BIN_[string toupper [string map {- {}} $binName]]"
    }
    define $defName $check
    return $check
}

########################################################################
# Looks for `bash` binary and dies if not found. On success, defines
# BIN_BASH to the full path to bash and returns that value. We
# _require_ bash because it's the SHELL value used in our makefiles.
proc wh-require-bash {} {
    set bash [wh-bin-define bash]
    if {"" eq $bash} {
        user-error "Our Makefiles require the bash shell."
    }
    return $bash
}

########################################################################
# Internal impl for wh-opt-bool-01 and wh-opt-bool-01-invert.
#
# args = {optName defName invert {descr {}}}
proc wh-opt-bool-01-impl {args} {
}


########################################################################
# Args: [-v] optName defName {descr {}}
#
# Checks [opt-bool $optName] and does [define $defName X] where X is 0
# for false and 1 for true. descr is an optional [msg-checking]
# argument which defaults to $defName. Returns X.
#
# If args[0] is -v then the boolean semantics are inverted: if
# the option is set, it gets define'd to 0, else 1. Returns the
# define'd value.
proc wh-opt-bool-01 {args} {
    set invert 0
    if {[lindex $args 0] eq "-v"} {
		set invert 1
		set args [lrange $args 1 end]
	}
    set optName [wh-lshift args]
    set defName [wh-lshift args]
    set descr [wh-lshift args]
    if {"" eq $descr} {
        set descr $defName
    }
    set rc 0
    msg-checking "$descr ... "
    if {[opt-bool $optName]} {
        if {0 eq $invert} {
            set rc 1
        } else {
            set rc 0
        }
    } elseif {0 ne $invert} {
        set rc 1
    }
    msg-result $rc
    define $defName $rc
    return $rc
}


########################################################################
# Curses!
#
# Jumps through numerous hoops to try to find ncurses libraries and
# appropriate compilation/linker flags. Returns 0 on failure, 1 on
# success, and defines (either way) LIB_CURSES to the various linker
# flags and CFLAGS_CURSES to the various CFLAGS (both empty strings if
# no lib is found).
#
# This impl prefers to use pkg-config to find ncurses and libpanel
# because various platforms either combine, or not, the wide-char
# versions of those libs into the same library (or not). If no
# pkg-config is available, OR the platform looks like Mac, then we
# simply make an educated guess and hope it works. On Mac pkg-config
# is not sufficient because the core system and either brew or
# macports can contain mismatched versions of ncurses and iconv, so on
# that platform we simply guess from the core system level, ignoring
# brew/macports options.
proc wh-check-ncurses {} {
    set pcBin [wh-bin-define pkg-config]
    msg-checking "Looking for \[n]curses... "
    set LIB_CURSES ""
    set CFLAGS_CURSES ""
    set rc 0
    if {"" ne $pcBin && $::tcl_platform(os)!="Darwin"} {
        # Some macOS pkg-config configurations alter library search paths, which make
        # the compiler unable to find lib iconv, so don't use pkg-config on macOS.
        set np ""
        foreach p {ncursesw ncurses} {
            if {[catch {exec $pcBin --exists $p}]} {
                continue
            }
            set np $p
            msg-result "Using pkg-config curses package \[$p]"
            break
        }
        if {"" ne $np} {
            set ppanel ""
            if {"ncursesw" eq $np} {
                if {![catch {exec $pcBin --exists panelw}]} {
                    set ppanel panelw
                }
            }
            if {"" eq $ppanel && ![catch {exec $pcBin --exists panel}]} {
                set ppanel panel
            }
            set CFLAGS_CURSES [exec $pcBin --cflags $np]
            set LIB_CURSES [exec $pcBin --libs $np]
            if {"" eq $ppanel} {
                # Apparently Mac brew has pkg-config for ncursesw but not
                # panel/panelw, but hard-coding -lpanel seems to work on
                # that platform.
                append LIB_CURSES " -lpanel"
            } else {
                append LIB_CURSES " " [exec $pcBin --libs $ppanel]
                # append CFLAGS_CURSES " " [exec $pcBin --cflags $ppanel]
                # ^^^^ appending the panel cflags will end up duplicating
                # at least one -D flag from $np's cflags, leading to
                # "already defined" errors at compile-time. Sigh. Note, however,
                # that $ppanel's cflags have flags which $np's do not, so we
                # may need to include those flags anyway and manually perform
                # surgery on the list to remove dupes. Sigh.
            }
        }
    }

    if {"" eq $LIB_CURSES} {
        puts "Guessing curses location (will fail for exotic locations)..."
        define HAVE_CURSES_H [cc-check-includes curses.h]
        if {[get-define HAVE_CURSES_H]} {
            # Linux has -lncurses, BSD -lcurses. Both have <curses.h>
            msg-result "Found curses.h"
            if {[wh-check-function-in-lib waddnwstr ncursesw]} {
                msg-result "Found -lncursesw"
                set LIB_CURSES "-lncursesw -lpanelw"
            } elseif {[wh-check-function-in-lib initscr ncurses]} {
                msg-result "Found -lncurses"
                set LIB_CURSES "-lncurses -lpanel"
            } elseif {[wh-check-function-in-lib initscr curses]} {
                msg-result "Found -lcurses"
                set LIB_CURSES "-lcurses -lpanel"
            }
        }
    }
    if {"" ne $LIB_CURSES} {
        set rc 1
        puts {************************************************************
If your build of fails due to missing ncurses functions
such as waddwstr(), make sure you have the ncursesw (with a
"w") development package installed. Some platforms combine
the "w" and non-w curses builds and some don't. Similarly,
it's easy to get a mismatch between libncursesw and libpanel,
so make sure you have libpanelw (if appropriate for your
platform).

The package may have a name such as libncursesw5-dev or
some such.
************************************************************}
    }
    define LIB_CURSES $LIB_CURSES
    define CFLAGS_CURSES $CFLAGS_CURSES
    return $rc
}
# /wh-check-ncurses
########################################################################

########################################################################
# Check for module-loading APIs (libdl/libltdl)...
#
# Looks for libltdl or dlopen(), the latter either in -ldl or built in
# to libc (as it is on some platforms. Returns 1 if found, else
# 0. Either way, it `define`'s:
#
#  - HAVE_LIBLTDL to 1 or 0 if libltdl is found/not found
#  - HAVE_LIBDL to 1 or 0 if dlopen() is found/not found
#  - LDFLAGS_MODULE_LOADER one of ("-lltdl", "-ldl", or ""), noting that
#    the string may legally be empty on some platforms if HAVE_LIBDL is true.
proc wh-check-module-loader {} {
    msg-checking "Looking for module-loader APIs... "
    if {99 ne [get-define LDFLAGS_MODULE_LOADER]} {
        if {1 eq [get-define HAVE_LIBLTDL 0]} {
            msg-result "(cached) libltdl"
            return 1
        } elseif {1 eq [get-define HAVE_LIBDL 0]} {
            msg-result "(cached) libdl"
            return 1
        }
        # else: wha???
    }
    set HAVE_LIBLTDL 0
    set HAVE_LIBDL 0
    set LDFLAGS_MODULE_LOADER ""
    set rc 0
    puts "" ;# cosmetic kludge for cc-check-XXX
    if {[cc-check-includes ltdl.h] && [cc-check-function-in-lib lt_dlopen ltdl]} {
        set HAVE_LIBLTDL 1
        set LDFLAGS_MODULE_LOADER "-lltdl"
        puts " - Got libltdl."
        set rc 1
    } elseif {[cc-with {-includes dlfcn.h} {
        cctest -link 1 -declare "extern char* dlerror(void);" -code "dlerror();"}]} {
        puts " - This system can use dlopen() w/o -ldl."
        set HAVE_LIBDL 1
        set LDFLAGS_MODULE_LOADER ""
        set rc 1
    } elseif {[cc-check-includes dlfcn.h]} {
        set HAVE_LIBDL 1
        set rc 1
        if {[cc-check-function-in-lib dlopen dl]} {
            puts " - dlopen() needs libdl."
            set LDFLAGS_MODULE_LOADER "-ldl"
        } else {
            puts " - dlopen() not found in libdl. Assuming dlopen() is built-in."
            set LDFLAGS_MODULE_LOADER ""
        }
    }
    define HAVE_LIBLTDL $HAVE_LIBLTDL
    define HAVE_LIBDL $HAVE_LIBDL
    define LDFLAGS_MODULE_LOADER $LDFLAGS_MODULE_LOADER
    return $rc
}


########################################################################
# Opens the given file, reads all of its content, and returns it.
proc wh-file-content {fname} {
    set fp [open $fname r]
    set rc [read $fp]
    close $fp
    return $rc
}

########################################################################
# Returns the contents of the given file as an array, with the EOL
# stripped from each input line.
proc wh-file-content-list {fname} {
    set fp [open $fname r]
    set rc {}
    while { [gets $fp line] >= 0 } {
        lappend rc $line
    }
    return $rc
}

########################################################################
# Checks the compiler for compile_commands.json support. If passed an
# argument it is assumed to be the name of an autosetup boolean config
# option to explicitly DISABLE the compile_commands.json support.
#
# Returns 1 if supported, else 0. Defines MAKE_COMPILATION_DB to "yes"
# if supported, "no" if not.
proc wh-check-compile-commands {{configOpt {}}} {
    msg-checking "compile_commands.json support... "
    if {"" ne $configOpt && [opt-bool $configOpt]} {
        msg-result "explicitly disabled"
        define MAKE_COMPILATION_DB no
        return 0
    } else {
        if {[cctest -lang c -cflags {/dev/null -MJ} -source {}]} {
            # This test reportedly incorrectly succeeds on one of
            # Martin G.'s older systems.
            msg-result "compiler supports compile_commands.json"
            define MAKE_COMPILATION_DB yes
            return 1
        } else {
            msg-result "compiler does not support compile_commands.json"
            define MAKE_COMPILATION_DB no
            return 0
        }
    }
}

########################################################################
# Uses [make-template] to creates makefile(-like) file $filename from
# $filename.in but explicitly makes the output read-only, to avoid
# inadvertent editing (who, me?).
#
# The second argument is an optional boolean specifying whether to
# `touch` the generates files. This can be used as a workaround for
# cases where (A) autosetup does not update the file because it was
# not really modified and (B) the file *really* needs to be updates to
# the please build process. Pass any non-0 value to enable touching.
#
# The argument may be a list of filenames.
proc wh-make-from-dot-in {filename {touch 0}} {
  foreach f $filename {
    catch { exec chmod u+w $f }
    make-template $f.in $f
    if {0 != $touch} {
      puts "Touching $f"
      catch { exec touch $f }
    }
    catch { exec chmod u-w $f }
  }
}

########################################################################
# Checks for the boolean configure option named by $flagname. If set,
# it checks if $CC seems to refer to gcc. If it does (or appears to)
# then it defines CC_PROFILE_FLAG to "-pg" and returns 1, else it
# defines CC_PROFILE_FLAG to "" and returns 0.
#
# Note that the resulting flag must be added to both CFLAGS and
# LDFLAGS in order for binaries to be able to generate "gmon.out".  In
# order to avoid potential problems with escaping, space-containing
# tokens, and interfering with autosetup's use of these vars, this
# routine does not directly modify CFLAGS or LDFLAGS.
proc wh-check-profile-flag {{flagname profile}} {
  if {[opt-bool $flagname]} {
    set CC [get-define CC]
    regsub {.*ccache *} $CC "" CC
    # ^^^ if CC="ccache gcc" then [exec] treats "ccache gcc" as a
    # single binary name and fails. So strip any leading ccache part
    # for this purpose.
    if { ![catch { exec $CC --version } msg]} {
      if {[string first gcc $CC] != -1} {
        define CC_PROFILE_FLAG "-pg"
        return 1
      }
    }
  }
  define CC_PROFILE_FLAG ""
  return 0
}

Changes to compile_flags.txt.

1
2
3
4
5

6
7
8
9
10
11
12
13
14
15
16
1
2
3
4

5
6
7
8
9
10
11
12
13
14
15
16




-
+











-std=c89
-I
include
-I
src
lib
-isystem
/usr/local/include
-isystem
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/12.0.0/include
-isystem
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include
-isystem
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
-isystem
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks

Deleted config.make.in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

























































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# Example of a typical Makefile template for autosetup

# Tools. CC is standard. The rest are via cc-check-tools
CC = @CC@
RANLIB = @RANLIB@
AR = @AR@
STRIP = @STRIP@

# FLAGS/LIBS
CFLAGS += @CFLAGS@ @CC_PROFILE_FLAG@
LDFLAGS += @LDFLAGS@ @CC_PROFILE_FLAG@
LDLIBS += @LIBS@
#LDLIBS += -lsqlite3 -lz
LDFLAGS_MODULE_LOADER += @LDFLAGS_MODULE_LOADER@

# ??? HAVE_DLOPEN := @HAVE_DLOPEN@
HAVE_LIBDL := @HAVE_LIBDL@
HAVE_LIBLTDL := @HAVE_LIBLTDL@
#HAVE_LT_DLOPEN := @HAVE_LT_DLOPEN@

ENABLE_MODULES ?= @FSL_ENABLE_MODULE_LOADER@
#ifeq (1,$(HAVE_DLOPEN))
#  ENABLE_MODULES := 1
#endif
#ifeq (1,$(HAVE_LT_DLOPEN))
#  ENABLE_MODULES := 1
#endif

# Install destination
prefix := @prefix@
exec_prefix = @exec_prefix@
DESTDIR ?=

CONFIG.MAKE := $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
#TOP_SRCDIR_ABS := $(dir $(realpath $(CONFIG.MAKE)))
TOP_SRCDIR_REL := $(patsubst %/,%,$(dir $(CONFIG.MAKE)))
TOP_SRCDIR_ABS := $(realpath $(TOP_SRCDIR_REL))
#$(error TOP_SRCDIR_REL=$(TOP_SRCDIR_REL))

SRC.DIR := $(TOP_SRCDIR_REL)/src

# Project-specific CFLAGS
TOP_INCDIR := $(TOP_SRCDIR_REL)/include
COMPAT_DIR := $(TOP_SRCDIR_REL)/compat
#CPPFLAGS += -D_GNU_SOURCE -Wall -Werror -I. -I$(TOP_INCDIR)
CPPFLAGS += -I. -I$(TOP_INCDIR) -I$(SRC.DIR)
# -I$(COMPAT_DIR)/javavm/export -I$(COMPAT_DIR)/tcl-8.6/generic
ifneq (,$(wildcard $(HOME)/include/*))
  # This is admittedly primarily for my own sake!
  CPPFLAGS += -I$(HOME)/include
endif

ifeq (,$(filter tcc,$(CC)))
  # Assume gcc-compatible compilation flags...
  CFLAGS += -Wall -Werror -Wsign-compare -pedantic
#??? -fno-strict-aliasing
  CFLAGS += @CC_FLAG_C99@
endif
# /tcc

# Enable MAKE_COMPILATION_DB = yes to generate a JSON compilation database. For
# each *.c source file being compiled, a corresponding JSON file will be created
# in the './compile_commands' sub-directory, and will be used to generate the
# 'compile_commands.json' compilation database in the repository root. This is
# only available with compilers that support the '-MJ' option (e.g., clang).
MAKE_COMPILATION_DB = @MAKE_COMPILATION_DB@


FSL_ENABLE_READLINE := @FSL_ENABLE_READLINE@
LDFLAGS_READLINE := @lib_readline@

ifeq ($(MAKE_COMPILATION_DB),yes)
compdb_dir = compile_commands
mkdir_compdb = $(TOP_SRCDIR_REL)/$(compdb_dir)
$(mkdir_compdb):
	@mkdir -p $@

compdb_file = $(TOP_SRCDIR_REL)/$(compdb_dir)/$(subst /,-,$@.json)
compdb_args = -MJ $(compdb_file)
CFLAGS += $(compdb_args)
else
mkdir_compdb =
endif


CLEAN_FILES += *.o lib*.a *.so

ShakeNMake.QUIET ?= @BUILD_QUIETLY@
ShakeNMake.BIN.INSTALL := @BIN_INSTALL@

Deleted configure.

1
2
3



-
-
-
#!/bin/sh
dir="`dirname "$0"`/autosetup"
WRAPPER="$0"; export WRAPPER; exec "`"$dir/autosetup-find-tclsh"`" "$dir/autosetup" "$@"

Deleted fnc/Makefile.in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36




































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
all:
include ../subdir-inc.make
LIB_CURSES := @LIB_CURSES@
ifeq (,$(LIB_CURSES))
$(error Expecting LIB_CURSES to be set by the configure process.)
endif
CFLAGS_CURSES := @CFLAGS_CURSES@
LIBF_DIR := $(TOP_DIR)/src
CPPFLAGS += -I$(LIBF_DIR) $(CFLAGS_CURSES)
DISTCLEAN_FILES += Makefile

########################################################################
# To build fnc, we need the curses and pthread libraries.
# -lz is for libfossil
# -liconv is for libfossil on macOS
# -lutil is... ???
# -lm is for sqlite3
FNC_LDFLAGS := $(LIBF_DIR)/libfossil.o $(LIBF_DIR)/sqlite3.o
PLATFORM := $(shell sh -c 'uname 2>/dev/null || echo Unknown')
ifneq ($(filter $(PLATFORM),Darwin),)
  FNC_LDFLAGS += -liconv
endif
FNC_LDFLAGS += -lm
FNC_LDFLAGS += $(LIB_CURSES) -lutil -lz -lpthread

# This is needed for Mac builds, else they don't see the
# wide-char curses APIs:
CPPFLAGS += -D_XOPEN_SOURCE_EXTENDED

fnc.BIN.OBJECTS += fnc.o
fnc.BIN.LDFLAGS := $(FNC_LDFLAGS)
$(eval $(call ShakeNMake.CALL.RULES.BIN,fnc))
all: $(fnc.BIN)

ShakeNMake.install.bins := $(fnc.BIN)
ShakeNMake.install.man1 := fnc.1

Deleted fnc/fnc.1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
671
672
673
674
675
676
677
678
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




































































































































































































































































































































































































































































































































































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
.\"
.\" Copyright (c) 2021 Mark Jamsek <mark@jamsek.com>
.\"
.\" Permission to use, copy, modify, and distribute this software for any
.\" purpose with or without fee is hereby granted, provided that the above
.\" copyright notice and this permission notice appear in all copies.
.\"
.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
.\"
.Dd $Mdocdate$
.Dt FNC 1
.Os
.Sh NAME
.Nm fnc
.Nd Read-only ncurses-based Fossil repository browser
.Sh SYNOPSIS
.Nm
.Op Ar command
.Op Fl h | -help
.Nm
.Op Fl h | -help
.Op Fl v | -version
.Nm
.Cm timeline
.Op Fl Cz
.Op Fl T Ar tag
.Op Fl b Ar branch
.Op Fl c Ar commit
.Op Fl n Ar number
.Op Fl t Ar type
.Op Fl u Ar user
.Op Ar path
.Nm
.Cm diff
.Op Fl Ciw
.Op Fl x Ar number
.Op Ar artifact1 Op Ar artifact2
.Op Ar path ...
.Nm
.Cm tree
.Op Fl C
.Op Fl c Ar commit
.Op Ar path
.Nm
.Cm blame
.Op Fl C
.Op Fl c Ar commit Op Fl r
.Op Fl n Ar number
.Ar path
.Nm
.Cm branch
.Op Fl Ccopr
.Op Fl a Ar date | Fl b Ar date
.Op Fl s Ar order
.Op Ar glob
.Nm
.Op Ar path
.Sh DESCRIPTION
.Nm
is an interactive read-only browser for
.Xr fossil 1
repositories,
and supports multiple views to display repository data:
.Bl -tag -width Ds
.It Timeline view
Display commits from the repository's history in chronologically
descending order.
.Br
If no
.Ar command
or
.Ar arg
are specified, or just a
.Ar path
is passed,
.Nm
will default to displaying this view.
.It Diff view
Display changes introduced in the specified commit, or between two repository
artifacts.
.It Tree view
Display navigable tree reflecting the repository state as at the specified
commit.
.It Blame view
Display and annotate each line in the given file with the hyperlinked historical
version that last modified the line.
.It Branch view
Display navigable list of all repository branches.
.El
.Pp
.Nm
provides both global and command-specific options and in-app key
bindings.  Global options are specified absent a command name, and
are as follows:
.Bl -tag -width 6v
.It Fl h , -help
Display program help and usage information then exit.
.It Fl v , -version
Display program version then exit.
.El
.Pp
Note that any global options preceding a command name will be
interpreted as the command-specific variant if such an option exists.
.Pp
Global key bindings are as follows:
.Bl -tag -width Ds
.It Cm H, ?, F1
Open in-app help.
.It Cm Tab
Switch focus between open views.
.It Cm f
Toggle the active view between fullscreen and splitscreen mode.  Note
that
.Nm
will open nested views in splitscreen mode if the terminal window is
equal to or greater than 110 columns wide.
.It Cm Q
Immediatey quit
.Nm .
.It Cm q
Quit the active view.
.El
.Pp
Commands available to
.Nm
are as follows:
.Bl -tag -width 4v
.Tg log
.It Cm timeline Oo Fl C | -no-colour Oc Oo Fl T | -tag Ar tag Oc \
Oo Fl b | -branch Ar branch Oc Oo Fl c | -commit Ar commit Oc \
Oo Fl h | -help Oc  Oo Fl n | -limit Ar n Oc  Oo Fl t | -type Ar type Oc \
Oo Fl u | -username Ar user Oc Oo Fl z | -utc Oc  Op Ar path
.Dl (aliases: Cm log , Cm tl , Cm time , Cm ti )
Display commit history of a repository.  If
.Ar path
is specified, only commits that modified the file(s) at this path will populate
the timeline.  The
.Ar path
may be absolute, relative to the current working directory, or relative to the
repository root.  This command must be executed from within or below the top
level directory of the repository; that is,
.Nm
assumes a local checkout is open in or above the current working directory.
.Pp
If no command is explicitly specified, this command will be executed by
default.
.Pp
Options for
.Cm fnc timeline
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable colourised timeline, which is enabled by default on supported
terminals. If this option is not used, colour can be toggled with the
.Sy c
timeline view key binding as documented below.
.It Fl T , -tag Ar tag
Only display commits with T cards containing
.Ar tag .
By default,
.Nm
will indiscriminately display all commits irrespective of which T cards
are attached to the commit manifest.
.It Fl b , -branch Ar branch
Display commits that are members of the specified
.Ar branch .
The expected argument is the symbolic name of a branch. By default,
.Nm
will display all commits irrespective of the branch on which they
reside.
.It Fl c , -commit Ar commit
Open the timeline from the check-in identified by
.Ar commit .
The expected argument is either the name of a branch, which will resolve
to the latest commit on the given branch, or (a unique abbreviated
prefix of) a valid commit UUID SHA1 or SHA3 hash. When this option is
not supplied,
.Nm
will open the timeline to the latest leaf on the repository tree.  For a
complete list of valid arguments this option accepts, see
.Lk https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki \
"Fossil's Check-in Names".
.It Fl h , -help
Display timeline command help and usage information then exit.
.It Fl n , -limit Ar n
Limit timeline to the
latest
.Ar n
commits.
By default,
.Nm
will load the entire history of the repository's local checkout.
Negative values are a no-op.
.It Fl t , -type Ar type
Only display
.Ar type
commits. Valid
.Ar type
values are as follows:
.Bl -column YXZ description
.Sy ci Ta check-in
.Sy w Ta wiki
.Sy t Ta ticket
.Sy e Ta technote
.Sy f Ta forum post
.El
.Pp
By default, when this option is not supplied,
.Nm
will indiscriminately load all commits irrespective of
.Ar type .
Note that this is a repeatable flag (e.g.,
.Nm
.Cm timeline
.Cm -t e -t t Ns
).
.It Fl u , -username Ar user
Only display commits authored by
.Ar user .
.It Fl z , -utc
Use Coordinated Universal Time (UTC) rather than local time when
displaying commit dates and timestamps.
.El
.Pp
Key bindings for
.Cm fnc timeline
are as follows:
.Bl -tag -width Ds
.It Cm Arrow-down, j, >, \&.
Move selection cursor down the timeline.
.It Cm Arrow-up, k, <, \&,
Move selection cursor up the timeline.
.It Cm Ctrl+f, Page-down
Move selection cursor one page down the timeline.
.It Cm Ctrl+b, Page-up
Move selection cursor one page up the timeline.
.It Cm G, End
Move selection cursor to the last commit on the timeline (i.e., oldest commit
in the repository).
.It Cm gg, Home
Move selection cursor to the first commit on the timeline (i.e., newest commit
in the repository).
.It Cm Enter, Space
Open a
.Cm diff
view displaying the changeset of the currently selected commit.
.It Cm c
Toggle colourised timeline. On supported terminals,
.Nm
will default to displaying the timeline in colour.
.It Cm t
Display the tree of the repository corresponding to the currently selected
commit.
.It Cm /
Prompt to enter a search term to begin searching for commits matching
the pattern provided.  The search term is an extended regular expression,
which is cross-referenced against a commit's comment, the username of
its author, branch, and UUID SHA1 or SHA3 hash.  See
.Xr re_format 7
for regular expression syntax.
.It Cm n
Find the next commit that matches the current search term.  The search
will continue until either a match is found or the earliest commit on
the timeline is consumed.
.It Cm N
Find the previous commit that matches the current search term.  The
search will continue until either a match is found or the latest commit
on the timeline is consumed.
.El
.Tg di
.It Cm diff Oo Fl C | -no-colour Oc Oo Fl h | -help Oc Oo Fl i | -invert \
Oc Oo Fl w | -whitespace Oc Oo Fl x | -context Ar n Oc \
Oo Ar artifact1 Oo Ar artifact2 Oc Oc Op Ar path ...
.Dl (alias: Cm di )
Display the differences between two repository artifacts, or between the local
changes on disk and a given commit.  If neither
.Ar artifact1
nor
.Ar artifact2
are specified,
.Nm
will diff the local changes on disk against the version on which the current
checkout is based.  If only
.Ar artifact1
is specified,
.Nm
will diff the current checkout, including any local changes on disk, against
this version.  When both arguments are specified, the changes between these two
versions will be displayed.  If supplied,
.Nm
will filter diffs between commits by
.Ar path
so that only changes involving the file(s) identified are displayed.  Paths may
be absolute, relative to the current working directory, or relative to the
repository root.  Both
.Ar artifact1
and
.Ar artifact2
must be of the same type, which is expected to be either a symbolic check-in
name, tag, (unique abbreviated prefix of) a commit or blob artifact UUID SHA1
or SHA3 hash, or an ISO 8601 formatted date. Both artifact arguments must be
supplied when diffing blobs; any following non-option arguments are invalid
and will be ignored.
.Pp
Options for
.Cm fnc diff
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured diff output, which is enabled by default on supported
terminals. If this option is not used, colour can be toggled with the
.Sy c
diff view key binding as documented below.
.It Fl h , -help
Display diff command help and usage information then exit.
.It Fl i , -invert
Invert the difference between artifacts when displaying the diff.
.It Fl w , -whitespace
Ignore whitespace-only changes when displaying the diff.
.It Fl x , -context Ar n
Set
.Ar n
context lines to be shown in the diff.  By default, 5 context lines are
shown. Negative values are a no-op.
.El
.Pp
Key bindings for
.Cm fnc diff
are as follows:
.Bl -tag -width Ds
.It Cm c
Toggle coloured diff output. On supported terminals,
.Nm
will default to displaying changes and diff metadata in colour.
.It Cm i
Toggle inversion of diff output.
.It Cm v
Toggle verbosity of diff output. By default,
.Nm
will display the entire content of newly added or deleted files.
.It Cm w
Toggle whether whitespace-only changes are ignored when comparing lines in the
diff.
.It Cm Arrow-down, j
Scroll down one line of diff output.
.It Cm Arrow-up, k
Scroll up one line of diff output.
.It Cm Ctrl+f, Page-down, Space
Scroll down one page of diff output.
.It Cm Ctrl+b, Page-up
Scroll up one page of diff output.
.It Cm G, End
Scroll to the end of the view (i.e., last line of diff output).
.It Cm gg, Home
Scroll to the top of the view (i.e., first line of diff output).
.It Cm \&-, \&_
Decrease the number of context lines shown in diff output.
.It Cm \&=, \&+
Increase the number of context lines shown in diff output.
.It Cm Ctrl+k, K, <, \&,
Move up the
.Cm timeline
to the previous (i.e., more recent) commit and display its diff.
.It Cm Ctrl+j, J, >, \&.
Move down the
.Cm timeline
to the next (i.e., earlier) commit and display its diff.
.It Cm /
Prompt to enter a search term to begin searching the diff output for
lines matching the pattern provided.  The search term is an extended
regular expression, which is documented in
.Xr re_format 7 .
.It Cm n
Find the next line that matches the current search term.
.It Cm N
Find the previous line that matches the current search term.
.El
.Tg dir
.It Cm tree Oo Fl C | -no-colour Oc Oo Fl c | -commit Ar commit Oc \
Oo Fl h | -help Oc Op Ar path
.Dl (aliases: Cm dir , Cm tr )
Display navigable, hierarchical tree of a repository.  If a
.Ar path
is specified, display tree nodes of this path.  The
.Ar path
may be absolute, relative to the current working directory, or relative to the
repository root.  With no options passed, the tree will reflect the state of the
latest commit on trunk.  This command must be executed from within or below the
top level directory of the repository; that is,
.Nm
assumes a local checkout is open in or above the current working directory.
.Pp
Tree nodes are lexicographically ordered and may be postfixed with an identifier
corresponding to the mode of the file object on disk as returned by
.Xr lstat 2 :
.Bl -column YXZ description
.It / Ta directory
.It * Ta executable
.It @ Ta symbolic link
.El
.Pp
Nodes representing symbolic links are also annotated with the path of the
source file.
.Pp
Options for
.Cm fnc tree
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured output, which is enabled by default on supported terminals.
If this option is not used, colour can be toggled with the
.Sy c
tree view key binding as documented below.
.It Fl c , -commit Ar commit
The displayed tree will reflect the state of the repository as at the check-in
identified by
.Ar commit .
The expected argument is either the name of a branch, which will resolve
to the latest commit on the given branch, or (a unique abbreviated
prefix of) a valid commit UUID SHA1 or SHA3 hash.  For a complete list of valid
arguments this option accepts, see
.Lk https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki \
"Fossil's Check-in Names".
.It Fl h , -help
Display tree command help and usage information then exit.
.El
.Pp
Key bindings for
.Cm fnc tree
are as follows:
.Bl -tag -width Ds
.It Cm Enter, Arrow-right, l
Enter the currently selected directory, or open a
.Cm blame
view of the currently selected file.
.It Cm Backspace, Arrow-left, h
Move up a level to the parent directory.  This is a no-op when in the root tree.
.It Cm Arrow-down, j
Move selection cursor one node down the tree.
.It Cm Arrow-up, k
Move selection cursor one node up the tree.
.It Cm Page-down, Ctrl+f
Move selection cursor one page down the tree.
.It Cm Page-up, Ctrl+b
Move selection cursor one page up the tree.
.It Cm Home, gg
Move selection cursor to the first node in the tree.
.It Cm End, G
Move selection cursor to the last node in the tree.
.It Cm c
Toggle coloured output. On supported terminals,
.Nm
will default to displaying the tree in colour.
.It Cm t
Open
.Cm timeline
view for the currently selected tree node.  This will display the timeline of
all commits that involve the versioned file(s) corresponding to the selected
node.
.It Cm i
Show SHA hash UUID for all file nodes displayed in the tree.
.It Cm /
Prompt to enter a search term to begin searching the tree for nodes matching the
entered pattern.  The search term is an extended regular expression, as
documented in
.Xr re_format 7 ,
and is matched against the path of each tree node.
.It Cm n
Find the next tree node that matches the current search pattern.
.It Cm N
Find the previous tree node that matches the current search pattern.
.El
.Tg praise
.It Cm blame Oo Fl C | -no-colour Oc \
Oo Fl c | -commit Ar commit Oo Fl r | -reverse Oc Oc Oo Fl h | -help Oc \
Oo Fl n | -limit Ar n Oc Ar path
.Dl (aliases: Cm praise , Cm annotate , Cm bl , Cm pr , Cm an )
Show commit attribution history for each line of the file at the specified
.Ar path ,
which may be absolute, relative to the current working directory, or relative to
the repository root.  This command must be executed from within or below the top
level directory of the repository; that is,
.Nm
assumes a local checkout is open in or above the current working directory.
.Pp
Options for
.Cm fnc blame
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured output, which is enabled by default on supported terminals.
If this option is not used, colour can be toggled with the
.Sy c
blame view key binding as documented below.
.It Fl c , -commit Ar commit
Start blame of file at the specified
.Ar path
from the check-in identified by
.Ar commit .
The expected argument is either the name of a branch, which will resolve
to the latest commit on the given branch, or (a unique abbreviated
prefix of) a valid commit UUID SHA1 or SHA3 hash. When this option is
not supplied,
.Nm
will blame the version of the file from the current checkout.  For a complete
list of valid arguments this option accepts, see
.Lk https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki \
"Fossil's Check-in Names".
.It Fl h , -help
Display blame command help and usage information then exit.
.It Fl n , -limit Ar n
Limit depth of blame history to
.Ar n
commits or seconds.  The latter is denoted by a postfixed 's' (e.g., 30s).
With this option,
.Nm
will traverse either as many commits as specified, or as possible in the
specified time limit.  By default,
.Nm
will traverse the entire historical record of the file, which can be expensive
for large files that span many commits. Use this option for a faster, more
targeted annotation.
.It Fl r , -reverse
Reverse annotate the file starting from a historical commit and move forward in
time. That is, rather than show the most recent change to each line, show the
first time each line was modified by a subsequent commit after the specified
.Ar commit .
(Requires \fB\-c\fP|\fB\-\-commit\fP.)
.El
.Pp
Key bindings for
.Cm fnc blame
are as follows:
.Bl -tag -width Ds
.It Cm Arrow-down, j
Move selection cursor down one line.
.It Cm Arrow-up, k
Move selection cursor up one line.
.It Cm Page-down, Ctrl+f
Move selection cursor down one page.
.It Cm Page-up, Ctrl+b
Move selection cursor up one page.
.It Cm Home, gg
Move selection cursor to the first line in the file.
.It Cm End, G
Move selection cursor to the last line in the file.
.It Cm Enter
Display the
.Cm diff
of the commit corresponding to the currently selected line.
.It Cm b
Blame the version of the file corresponding to the commit in the currently
selected line.
.It Cm p
Blame the version of the file corresponding to the parent of the commit in
the currently selected line.
.It Cm B, Backspace
Reload the previous blamed version of the file.
.It Cm c
Toggle coloured output. On supported terminals,
.Nm
will default to displaying the blamed file in colour.
.It Cm /
Prompt to enter a search term to begin searching the file for tokens matching
the entered pattern.  The search term is an extended regular expression, as
documented in
.Xr re_format 7 .
.It Cm n
Find the next token that matches the current search pattern.
.It Cm N
Find the previous token that matches the current search pattern.
.El
.Tg tag
.It Cm branch Oo Fl C | -no-colour Oc Oo Fl -after Ar date | \
Fl -before Ar date Oc Oo Fl h | -help Oc Oo Fl -open | Fl -closed Oc \
Oo Fl p | -no-private Oc Oo Fl r | -reverse Oc \
Oo Fl s | -sort Ar order Oc Op Ar glob
.Dl (aliases: Cm tag , Cm br )
Display navigable list of repository branches. If
.Ar glob ,
is specified, only display branches matching the pattern provided. Pattern
matching comparisons depend on the
.Xr sqlite3 1
.B
LIKE
operator, which only folds case for the ASCII character set.  This
command must be executed from within or below the top level directory of the
repository; that is,
.Nm
assumes a local checkout is open in or above the current working directory.
.Pp
Branches are lexicographically ordered by default, and are prefixed with an
identifier corresponding to the branch state (i.e., open/closed). The
current and private branches are additionally annotated with a postfixed
identifier:
.Bl -column ABCDEFGHIJ description
.It +dev-foo Ta open
.It -rm-bar Ta closed
.It +trunk@ Ta current
.It +wip-baz* Ta private
.El
.Pp
All branches, irrespective of state or privacy, are displayed by default, but
can be filtered based on several characteristics.
.Pp
Options for
.Cm fnc branch
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured output, which is enabled by default on supported terminals.
If this option is not used, colour can be toggled with the
.Sy c
branch view key binding as documented below.
.It Fl a , -after Ar date
Display only those branches with activity after the specified
.Ar date .
.It Fl b , -before Ar date
Display only those branches with activity before the specified
.Ar date .
.It Fl c , -close
Display only closed branches.
.It Fl h , -help
Display branch command help and usage information then exit.
.It Fl o , -open
Display only opened branches.
.It Fl p , -no-private
Do not show private branches, which are included in the list of displayed
branches by default.
.It Fl r , -reverse
Reverse the order in which branches are displayed.
.It Fl s , -sort Ar order
Sort branches by
.Ar order .
Valid
.Ar order
values are as follows:
.Bl -column YXZ description
.Sy mru Ta most recently used
.Sy state Ta open/closed state
.El
.Pp
Branches are sorted in lexicographical order by default.
.El
.Pp
Key bindings for
.Cm fnc branch
are as follows:
.Bl -tag -width Ds
.It Cm Arrow-down, j
Move selection cursor down one branch.
.It Cm Arrow-up, k
Move selection cursor up one branch.
.It Cm Page-down, Ctrl+f
Move selection cursor down one page.
.It Cm Page-up, Ctrl+b
Move selection cursor up one page.
.It Cm Home, gg
Move selection cursor to the first branch in the list.
.It Cm End, G
Move selection cursor to the last branch in the list.
.It Cm Enter, Space
Display the
.Cm timeline
of the currently selected branch.
.It Cm c
Toggle coloured output.  On supported terminals,
.Nm
will default to displaying the branch list in colour.
.It Cm d
Toggle display of the date on which the branch last received changes.
.It Cm i
Toggle display of the SHA{1,3} hash that identifies branch, which is the hash
of the commit on the tip of said branch.
.It Cm t
Open the
.Cm tree
view of the currently selected branch.
.It Cm R, Ctrl+l
Reload the view with all repository branches, irrespective of which options
were used in this
.Cm fnc branch
invocation.
.It Cm /
Prompt to enter a search term to begin searching the list for branches matching
the entered pattern.  The search term is an extended regular expression, as
documented in
.Xr re_format 7 .
.It Cm n
Find the next branch that matches the current search pattern.
.It Cm N
Find the previous branch that matches the current search pattern.
.El
.El
.Sh EXIT STATUS
.Ex -std fnc
.Sh SEE ALSO
.Xr fossil 1 ,
.Xr re_format 7
.Xr sqlite3 1
.Sh AUTHOR
.An Mark Jamsek Aq Mt mark@jamsek.com

Deleted fnc/fnc.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
671
672
673
674
675
676
677
678
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
737
738
739
740
741
742
743
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
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
817
818
819
820
821
822
823
824
825
826
827
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
860
861
862
863
864
865
866
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
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
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
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
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
1342
1343
1344
1345
1346
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
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
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
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
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
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
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
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
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
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
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
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
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
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
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
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
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
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
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
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
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
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
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
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
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
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
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
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
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
3578
3579
3580
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
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
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
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
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
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
3931
3932
3933
3934
3935
3936
3937
3938
3939
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
3977
3978
3979
3980
3981
3982
3983
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
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
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
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
4182
4183
4184
4185
4186
4187
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
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
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
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
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
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
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
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
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
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
/*
 * Copyright (c) 2021 Mark Jamsek <mark@jamsek.com>
 * Copyright (c) 2013-2021 Stephan Beal <https://wanderinghorse.net>
 * Copyright (c) 2020 Stefan Sperling <stsp@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * This _POSIX_C_SOURCE bit really belongs in a config.h, but in the
 * name of expedience...
 */
#if defined __linux__
#  if !defined(_XOPEN_SOURCE)
#    define _XOPEN_SOURCE 700
/*
 * _POSIX_C_SOURCE >= 199309L needed for sigaction(), sigemptyset() on Linux,
 * but glibc docs claim that _XOPEN_SOURCE>=700 has the same effect, PLUS
 * we need _XOPEN_SOURCE>=500 for ncurses wide-char APIs on linux.
 */
#  endif
#  if !defined(_DEFAULT_SOURCE)
#    define _DEFAULT_SOURCE
/* Needed for strsep() on glibc >= 2.19. */
#  endif
#endif


#include <sys/queue.h>
#include <sys/ioctl.h>
#include <sys/stat.h>

#ifdef _WIN32
#include <windows.h>
#define ssleep(x) Sleep(x)
#else
#define ssleep(x) usleep((x) * 1000)
#endif
#include <ctype.h>
#include <curses.h>
#include <panel.h>
#include <locale.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <err.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
#include <pthread.h>
#include <libgen.h>
#include <regex.h>
#include <signal.h>
#include <wchar.h>
#include <langinfo.h>

#include "libfossil.h"

#define FNC_VERSION	0.4

/* Utility macros. */
#define MIN(a, b)	(((a) < (b)) ? (a) : (b))
#define MAX(a, b)	(((a) > (b)) ? (a) : (b))
#if !defined(CTRL)
#define CTRL(key)	((key) & 037)	/* CTRL+<key> input. */
#endif
#define nitems(a)	(sizeof((a)) / sizeof((a)[0]))
#define STRINGIFYOUT(s)	#s
#define STRINGIFY(s)	STRINGIFYOUT(s)
#define CONCATOUT(a, b)	a ## b
#define CONCAT(a, b)	CONCATOUT(a, b)
#define FILE_POSITION	__FILE__ ":" STRINGIFY(__LINE__)
#define FLAG_SET(f, b)	((f) |= (b))
#define FLAG_CHK(f, b)	((f) & (b))
#define FLAG_TOG(f, b)	((f) ^= (b))
#define FLAG_CLR(f, b)	((f) &= ~(b))

/* Application macros. */
#define PRINT_VERSION	STRINGIFY(FNC_VERSION)
#define DIFF_DEF_CTXT	5		/* Default diff context lines. */
#define DIFF_MAX_CTXT	64		/* Max diff context lines. */
#define SPIN_INTERVAL	200		/* Status line progress indicator. */
#define SPINNER		"\\|/-\0"
#define NULL_DEVICE	"/dev/null"
#define NULL_DEVICELEN	(sizeof(NULL_DEVICE) - 1)
#define KEY_ESCAPE	27
#if DEBUG
#define RC(r, fmt, ...)	fcli_err_set(r, "%s::%s " fmt,			\
			    __func__, FILE_POSITION, __VA_ARGS__)
#else
#define RC(r, fmt, ...) fcli_err_set(r, fmt, __VA_ARGS__)
#endif /* DEBUG */

/* Portability macros. */
#ifndef __OpenBSD__
#ifndef HAVE_STRTONUM
#  define strtonum(s, min, max, o) strtol(s, (char **)o, 10)
# endif /* HAVE_STRTONUM */
#endif

#if !defined(__dead)
#define __dead
#endif

#ifndef TAILQ_FOREACH_SAFE
/* Rewrite of OpenBSD 6.9 sys/queue.h for Linux builds. */
#define TAILQ_FOREACH_SAFE(var, head, field, tmp)			\
	for ((var) = ((head)->tqh_first);				\
		(var) != (NULL) && ((tmp) = TAILQ_NEXT(var, field), 1);	\
		(var) = (tmp))
#endif

/*
 * STAILQ was added to OpenBSD 6.9; fallback to SIMPLEQ for prior versions.
 * XXX This is an ugly hack; replace with a better solution.
 */
#ifdef __OpenBSD__
# ifndef STAILQ_HEAD
#  define STAILQ SIMPLEQ
# endif /* STAILQ_HEAD */
#endif /* OpenBSD */

#if defined __linux__
# ifndef strlcat
#  define strlcat(_d, _s, _sz) fnc_strlcat(_d, _s, _sz)
# endif /* strlcat */
# ifndef strlcpy
#  define strlcpy(_d, _s, _sz) fnc_strlcpy(_d, _s, _sz)
# endif /* strlcpy */
#endif /* __linux__ */

__dead static void	usage(void);
static void		usage_timeline(void);
static void		usage_diff(void);
static void		usage_tree(void);
static void		usage_blame(void);
static void		usage_branch(void);
static int		fcli_flag_type_arg_cb(fcli_cliflag const *);
static int		cmd_timeline(fcli_command const *);
static int		cmd_diff(fcli_command const *);
static int		cmd_tree(fcli_command const *);
static int		cmd_blame(fcli_command const *);
static int		cmd_branch(fcli_command const *);

/*
 * Singleton initialising global configuration and state for app startup.
 */
static struct fnc_setup {
	/* Global options. */
	const char	*cmdarg;	/* Retain argv[1] for use/err report. */
	const char	*sym;		/* Open view from this symbolic name. */
	const char	*path;		/* Optional path for timeline & tree. */
	int		 err;		/* Indicate fnc error state. */
	bool		 hflag;		/* Flag if --help is requested. */
	bool		 vflag;		/* Flag if --version is requested. */
	bool		 reverse;	/* Reverse branch sort or blame. */

	/* Timeline options. */
	struct artifact_types {
		const char	**values;
		short		  nitems;
	} *filter_types;		/* Only load commits of <type>. */
	union {
		const char	 *zlimit;
		int		  limit;
	} nrecords;			/* Number of commits to load. */
	const char	*filter_tag;	/* Only load commits with <tag>. */
	const char	*filter_branch;	/* Only load commits from <branch>. */
	const char	*filter_user;	/* Only load commits from <user>. */
	const char	*filter_type;	/* Placeholder for repeatable types. */
	bool		 utc;		/* Display UTC sans user local time. */

	/* Diff options. */
	const char	*context;	/* Number of context lines. */
	bool		 ws;		/* Ignore whitespace-only changes. */
	bool		 nocolour;	/* Disable colour in diff output. */
	bool		 quiet;		/* Disable verbose diff output. */
	bool		 invert;	/* Toggle inverted diff output. */

	/* Branch options. */
	const char	*before;	/* Last branch change before date. */
	const char	*after;		/* Last branch change after date. */
	const char	*sort;		/* Lexicographical, MRU, open/closed. */
	bool		 closed;	/* Show only closed branches. */
	bool		 open;		/* Show only open branches */
	bool		 noprivate;	/* Don't show private branches. */

	/* Command line flags and help. */
	fcli_help_info	  fnc_help;			/* Global help. */
	fcli_cliflag	  cliflags_global[3];		/* Global options. */
	fcli_command	  cmd_args[6];			/* App commands. */
	fcli_cliflag	  cliflags_timeline[11];	/* Timeline options. */
	fcli_cliflag	  cliflags_diff[7];		/* Diff options. */
	fcli_cliflag	  cliflags_tree[4];		/* Tree options. */
	fcli_cliflag	  cliflags_blame[6];		/* Blame options. */
	fcli_cliflag	  cliflags_branch[10];		/* Branch options. */
} fnc_init = {
	NULL,		/* cmdarg copy of argv[1] to aid usage/error report. */
	NULL,		/* sym(bolic name) of commit to open defaults to tip. */
	NULL,		/* path for tree to open or timeline to find commits. */
	0,		/* err fnc error state. */
	false,		/* hflag if --help is requested. */
	false,		/* vflag if --version is requested. */
	false,		/* reverse branch sort/annotation defaults to off. */
	NULL,		/* filter_types defaults to indiscriminate. */
	{0},		/* nrecords defaults to all commits. */
	NULL,		/* filter_tag defaults to indiscriminate. */
	NULL,		/* filter_branch defaults to indiscriminate. */
	NULL,		/* filter_user defaults to indiscriminate. */
	NULL,		/* filter_type temporary placeholder. */
	false,		/* utc defaults to off (i.e., show user local time). */
	NULL,		/* context defaults to five context lines. */
	false,		/* ws defaults to acknowledge whitespace. */
	false,		/* nocolour defaults to off (i.e., use diff colours). */
	false,		/* quiet defaults to off (i.e., verbose diff is on). */
	false,		/* invert diff defaults to off. */
	NULL,		/* before defaults to any time. */
	NULL,		/* after defaults to any time. */
	NULL,		/* sort by MRU or open/closed (dflt: lexicographical) */
	false,		/* closed only branches is off (defaults to all). */
	false,		/* open only branches is off by (defaults to all). */
	false,		/* noprivate is off (default to show private branch). */

	{ /* fnc_help global app help details. */
	    "A read-only ncurses browser for Fossil repositories in the "
	    "terminal.", NULL, usage
	},

	{ /* cliflags_global global app options. */
	    FCLI_FLAG_BOOL("h", "help", &fnc_init.hflag,
	    "Display program help and usage then exit."),
	    FCLI_FLAG_BOOL("v", "version", &fnc_init.vflag,
	    "Display program version number and exit."),
	    fcli_cliflag_empty_m
	},

	{ /* cmd_args available app commands. */
	    {"timeline", "tl\0time\0ti\0log\0",
	    "Show chronologically descending commit history of the repository.",
	    cmd_timeline, usage_timeline, fnc_init.cliflags_timeline},
	    {"diff", "di\0",
	    "Show changes to versioned files introduced with a given commit.",
	    cmd_diff, usage_diff, fnc_init.cliflags_diff},
	    {"tree", "tr\0dir\0",
	    "Show repository tree corresponding to a given commit",
	    cmd_tree, usage_tree, fnc_init.cliflags_tree},
	    {"blame", "bl\0praise\0pr\0annotate\0an\0",
	    "Show commit attribution history for each line of a file.",
	    cmd_blame, usage_blame, fnc_init.cliflags_blame},
	    {"branch", "br\0tag\0",
	    "Show navigable list of repository branches.",
	    cmd_branch, usage_branch, fnc_init.cliflags_branch},
	    {NULL, NULL, NULL, NULL, NULL}	/* Sentinel. */
	},

	{ /* cliflags_timeline timeline command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable colourised timeline, which is enabled by default on\n    "
            "supported terminals. Colour can also be toggled with the 'c' "
            "\n    key binding in timeline view when this option is not used."),
	    FCLI_FLAG("T", "tag", "<tag>", &fnc_init.filter_tag,
            "Only display commits with T cards containing <tag>."),
	    FCLI_FLAG("b", "branch", "<branch>", &fnc_init.filter_branch,
            "Only display commits that reside on the given <branch>."),
	    FCLI_FLAG("c", "commit", "<commit>", &fnc_init.sym,
            "Open the timeline from <commit>. Common symbols are:\n"
            "\tSHA{1,3} hash\n"
            "\tSHA{1,3} unique prefix\n"
            "\tbranch\n"
            "\ttag:TAG\n"
            "\troot:BRANCH\n"
            "\tISO8601 date\n"
            "\tISO8601 timestamp\n"
            "\t{tip,current,prev,next}\n    "
            "For a complete list of symbols see Fossil's Check-in Names:\n    "
            "https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki"),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display timeline command help and usage."),
	    FCLI_FLAG("n", "limit", "<n>", &fnc_init.nrecords.zlimit,
            "Limit display to <n> latest commits; defaults to entire history "
            "of\n    current checkout. Negative values are a no-op."),
	    FCLI_FLAG_X("t", "type", "<type>", &fnc_init.filter_type,
	    fcli_flag_type_arg_cb,
            "Only display <type> commits. Valid types are:\n"
            "\tci - check-in\n"
            "\tw  - wiki\n"
            "\tt  - ticket\n"
            "\te  - technote\n"
            "\tf  - forum post\n"
            "    n.b. This is a repeatable flag (e.g., -t ci -t w)."),
	    FCLI_FLAG("u", "username", "<user>", &fnc_init.filter_user,
            "Only display commits authored by <username>."),
	    FCLI_FLAG_BOOL("z", "utc", &fnc_init.utc,
            "Use UTC (instead of local) time."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_timeline. */

	{ /* cliflags_diff diff command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured diff output, which is enabled by default on\n    "
            "supported terminals. Colour can also be toggled with the 'c' "
            "\n    key binding in diff view when this option is not used."),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display diff command help and usage."),
	    FCLI_FLAG_BOOL("i", "invert", &fnc_init.invert,
            "Invert difference between artifacts. Inversion can also be "
            "toggled\n    with the 'i' key binding in diff view."),
	    FCLI_FLAG_BOOL("q", "quiet", &fnc_init.quiet,
            "Disable verbose diff output; that is, do not output complete"
            " content\n    of newly added or deleted files. Verbosity can also"
            " be toggled with\n    the 'v' key binding in diff view."),
	    FCLI_FLAG_BOOL("w", "whitespace", &fnc_init.ws,
            "Ignore whitespace-only changes when displaying diff. This option "
            "can\n    also be toggled with the 'w' key binding in diff view."),
	    FCLI_FLAG("x", "context", "<n>", &fnc_init.context,
            "Show <n> context lines when displaying diff; <n> is capped at 64."
            "\n    Negative values are a no-op."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_diff. */

	{ /* cliflags_tree tree command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured output, which is enabled by default on supported"
            "\n    terminals. Colour can also be toggled with the 'c' key "
            "binding when\n    this option is not used."),
	    FCLI_FLAG("c", "commit", "<commit>", &fnc_init.sym,
            "Display tree that reflects repository state as at <commit>.\n"
            "    Common symbols are:"
            "\n\tSHA{1,3} hash\n"
            "\tSHA{1,3} unique prefix\n"
            "\tbranch\n"
            "\ttag:TAG\n"
            "\troot:BRANCH\n"
            "\tISO8601 date\n"
            "\tISO8601 timestamp\n"
            "\t{tip,current,prev,next}\n    "
            "For a complete list of symbols see Fossil's Check-in Names:\n    "
            "https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki"),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display tree command help and usage."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_tree. */

	{ /* cliflags_blame blame command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured output, which is enabled by default on supported"
            "\n    terminals. Colour can also be toggled with the 'c' key "
            "binding when\n    this option is not used."),
	    FCLI_FLAG("c", "commit", "<commit>", &fnc_init.sym,
            "Start blame of specified file from <commit>. Common symbols are:\n"
            "\tSHA{1,3} hash\n"
            "\tSHA{1,3} unique prefix\n"
            "\tbranch\n"
            "\ttag:TAG\n"
            "\troot:BRANCH\n"
            "\tISO8601 date\n"
            "\tISO8601 timestamp\n"
            "\t{tip,current,prev,next}\n    "
            "For a complete list of symbols see Fossil's Check-in Names:\n    "
            "https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki"),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display blame command help and usage."),
            FCLI_FLAG("n", "limit", "<n>", &fnc_init.nrecords.zlimit,
	    "Limit depth of blame history to <n> commits or seconds. Denote the"
	    "\n    latter by postfixing 's' (e.g., 30s). Useful for large files"
	    " with\n    extensive history. Persists for the duration of the "
	    "session."),
            FCLI_FLAG_BOOL("r", "reverse", &fnc_init.reverse,
	    "Reverse annotate the file starting from a historical commit. "
	    "Rather\n    than show the most recent change of each line, show "
	    "the first time\n    each line was modified after the specified "
	    "commit. Requires -c|--commit."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_blame. */

	{ /* cliflags_branch branch command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured output, which is enabled by default on supported"
            "\n    terminals. Colour can also be toggled with the 'c' key "
            "binding when\n    this option is not used."),
	    FCLI_FLAG("a", "after", "<date>", &fnc_init.after,
            "Show branches with last activity occuring after <date>, which is\n"
            "    expected to be either an ISO8601 (e.g., 2020-10-10) or "
            "unambiguous\n    DD/MM/YYYY or MM/DD/YYYY formatted date."),
	    FCLI_FLAG("b", "before", "<date>", &fnc_init.before,
            "Show branches with last activity occuring before <date>, which is"
            "\n    expected to be either an ISO8601 (e.g., 2020-10-10) or "
            "unambiguous\n    DD/MM/YYYY or MM/DD/YYYY formatted date."),
            FCLI_FLAG_BOOL("c", "closed", &fnc_init.closed,
	    "Show closed branches only. Open and closed branches are listed by "
	    "\n    default."),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display branch command help and usage."),
            FCLI_FLAG_BOOL("o", "open", &fnc_init.open,
	    "Show open branches only. Open and closed branches are listed by "
	    "\n    default."),
            FCLI_FLAG_BOOL("p", "no-private", &fnc_init.noprivate,
	    "Do not show private branches, which are otherwise included in the"
	    "\n    list of displayed branches by default."),
            FCLI_FLAG_BOOL("r", "reverse", &fnc_init.reverse,
	    "Reverse the order in which branches are displayed."),
	    FCLI_FLAG("s", "sort", "<order>", &fnc_init.sort,
            "Sort branches by <order>. Available options are:\n"
            "\tmru   - most recently used\n"
            "\tstate - open/closed state\n    "
            "Branches are sorted in lexicographical order by default."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_blame. */
};

enum fsl_list_object {
	FNC_ARTIFACT_OBJ,
	FNC_COLOUR_OBJ
};

enum date_string {
	ISO8601_DATE_ONLY = 10,
	ISO8601_TIMESTAMP = 20
};

enum fnc_view_id {
	FNC_VIEW_TIMELINE,
	FNC_VIEW_DIFF,
	FNC_VIEW_TREE,
	FNC_VIEW_BLAME,
	FNC_VIEW_BRANCH
};

enum fnc_search_mvmnt {
	SEARCH_DONE,
	SEARCH_FORWARD,
	SEARCH_REVERSE
};

enum fnc_search_state {
	SEARCH_WAITING,
	SEARCH_CONTINUE,
	SEARCH_COMPLETE,
	SEARCH_NO_MATCH,
	SEARCH_FOR_END
};

enum fnc_colours {
	FNC_DIFF_META = 1,
	FNC_DIFF_MINUS,
	FNC_DIFF_PLUS,
	FNC_DIFF_CHNK,
	FNC_TREE_LINK,
	FNC_TREE_DIR,
	FNC_TREE_EXEC,
	FNC_COMMIT_ID,
	FNC_USER_STR,
	FNC_DATE_STR,
	FNC_TAGS_STR
};

enum fnc_diff_type {
	FNC_DIFF_CKOUT,
	FNC_DIFF_COMMIT,
	FNC_DIFF_BLOB,
	FNC_DIFF_WIKI
};

struct fnc_colour {
	regex_t	regex;
	uint8_t	scheme;
};

struct fsl_list_state {
	enum fsl_list_object	obj;
};

struct fnc_commit_artifact {
	fsl_buffer		 wiki;
	fsl_buffer		 pwiki;
	fsl_list		 changeset;
	fsl_uuid_str		 uuid;
	fsl_uuid_str		 puuid;
	fsl_id_t		 rid;
	fsl_id_t		 prid;
	char			*user;
	char			*timestamp;
	char			*comment;
	char			*branch;
	char			*type;
	enum fnc_diff_type	 diff_type;
};

struct fsl_file_artifact {
	fsl_card_F		*fc;
	enum fsl_ckout_change_e	 change;
};

TAILQ_HEAD(commit_tailhead, commit_entry);
struct commit_entry {
	TAILQ_ENTRY(commit_entry)	 entries;
	struct fnc_commit_artifact	*commit;
	int				 idx;
};

struct commit_queue {
	struct commit_tailhead	head;
	int			ncommits;
};

/*
 * The following two structs are used to construct the tree of the entire
 * repository; that is, from the root through to all subdirectories and files.
 */
struct fnc_repository_tree {
	struct fnc_repo_tree_node	*head;     /* Head of repository tree */
	struct fnc_repo_tree_node	*tail;     /* Final node in the tree. */
	struct fnc_repo_tree_node	*rootail;  /* Final root level node. */
};

struct fnc_repo_tree_node {
	struct fnc_repo_tree_node	*next;	     /* Next node in tree. */
	struct fnc_repo_tree_node	*prev;	     /* Prev node in tree. */
	struct fnc_repo_tree_node	*parent_dir; /* Dir containing node. */
	struct fnc_repo_tree_node	*sibling;    /* Next node in same dir */
	struct fnc_repo_tree_node	*children;   /* List of node children */
	struct fnc_repo_tree_node	*lastchild;  /* Last child in list. */
	char				*basename;   /* Final path component. */
	char				*path;	     /* Full pathname of node */
	fsl_uuid_str			 uuid;	     /* File artifact hash. */
	mode_t				 mode;	     /* File mode. */
	double				 mtime;	     /* Mod time of file. */
	uint_fast16_t			 pathlen;    /* Length of path. */
	uint_fast16_t			 nparents;   /* Path components sans- */
						     /* -basename. */
};

/*
 * The following two structs represent a given subtree within the repository;
 * for example, the top level tree and all its elements, or the elements of
 * the src/ directory (but not any members of src/ subdirectories).
 */
struct fnc_tree_object {
	struct fnc_tree_entry	*entries;  /* Array of tree entries. */
	int			 nentries; /* Number of tree entries. */
};

struct fnc_tree_entry {
	char			*basename; /* Final component of path. */
	char			*path;	   /* Full pathname of tree entry. */
	fsl_uuid_str		 uuid;	   /* File artifact hash. */
	mode_t			 mode;	   /* File mode. */
	double			 mtime;	   /* Modification time of file. */
	int			 idx;	   /* Index of this tree entry. */
};

/*
 * Each fnc_tree_object that is _not_ the repository root will have a (list of)
 * fnc_parent_tree(s) to be tracked.
 */
struct fnc_parent_tree {
	TAILQ_ENTRY(fnc_parent_tree)	 entry;
	struct fnc_tree_object		*tree;
	struct fnc_tree_entry		*first_entry_onscreen;
	struct fnc_tree_entry		*selected_entry;
	int				 selected_idx;
};

pthread_mutex_t fnc_mutex = PTHREAD_MUTEX_INITIALIZER;

struct fnc_tl_thread_cx {
	struct commit_queue	 *commits;
	struct commit_entry	**first_commit_onscreen;
	struct commit_entry	**selected_commit;
	fsl_db			 *db;
	fsl_stmt		 *q;
	regex_t			 *regex;
	char			 *path;	     /* Match commits involving path. */
	enum fnc_search_state	 *search_status;
	enum fnc_search_mvmnt	 *searching;
	int			  spin_idx;
	int			  ncommits_needed;
	/*
	 * XXX Is there a more elegant solution to retrieving return codes from
	 * thread functions while pinging between, but before we join, threads?
	 */
	int			  rc;
	bool			  tree_open;
	bool			  endjmp;
	bool			  timeline_end;
	sig_atomic_t		 *quit;
	pthread_cond_t		  commit_consumer;
	pthread_cond_t		  commit_producer;
};

struct fnc_tl_view_state {
	struct fnc_tl_thread_cx	 thread_cx;
	struct commit_queue	 commits;
	struct commit_entry	*first_commit_onscreen;
	struct commit_entry	*last_commit_onscreen;
	struct commit_entry	*selected_commit;
	struct commit_entry	*matched_commit;
	struct commit_entry	*search_commit;
	fsl_list		 colours;
	const char		*curr_ckout_uuid;
	char			*path;	     /* Match commits involving path. */
	int			 selected_idx;
	sig_atomic_t		 quit;
	pthread_t		 thread_id;
	bool			 colour;
};

struct fnc_pathlist_entry {
	TAILQ_ENTRY(fnc_pathlist_entry) entry;
	const char	*path;
	size_t		 pathlen;
	void		*data;  /* XXX May want to save id, mode, etc. */
};
TAILQ_HEAD(fnc_pathlist_head, fnc_pathlist_entry);

struct fnc_diff_view_state {
	struct fnc_view			*timeline_view;
	struct fnc_commit_artifact	*selected_commit;
	struct fnc_pathlist_head	*paths;
	fsl_buffer			 buf;
	fsl_list			 colours;
	FILE				*f;
	fsl_uuid_str			 id1;
	fsl_uuid_str			 id2;
	int				 first_line_onscreen;
	int				 last_line_onscreen;
	int				 diff_flags;
	int				 context;
	int				 sbs;
	int				 matched_line;
	int				 current_line;
	size_t				 ncols;
	size_t				 nlines;
	off_t				*line_offsets;
	bool				 eof;
	bool				 colour;
	bool				 showmeta;
};

TAILQ_HEAD(fnc_parent_trees, fnc_parent_tree);
struct fnc_tree_view_state {			  /* Parent trees of the- */
	struct fnc_parent_trees		 parents; /* -current subtree. */
	struct fnc_repository_tree	*repo;    /* The repository tree. */
	struct fnc_tree_object		*root;    /* Top level repo tree. */
	struct fnc_tree_object		*tree;    /* Currently displayed tree */
	struct fnc_tree_entry		*first_entry_onscreen;
	struct fnc_tree_entry		*last_entry_onscreen;
	struct fnc_tree_entry		*selected_entry;
	struct fnc_tree_entry		*matched_entry;
	fsl_list			 colours;
	char				*tree_label;  /* Headline string. */
	fsl_uuid_str			 commit_id;
	fsl_id_t			 rid;
	int				 ndisplayed;
	int				 selected_idx;
	bool				 colour;
	bool				 show_id;
};

struct fnc_blame_line {
	fsl_uuid_str	id;
	bool		annotated;
};

struct fnc_blame_cb_cx {
	struct fnc_view		*view;
	struct fnc_blame_line	*lines;
	fsl_uuid_str		 commit_id;
	fsl_uuid_str		 root_commit;
	int			 nlines;
	bool			*quit;
};

typedef int (*fnc_cancel_cb)(void *);

struct fnc_blame_thread_cx {
	struct fnc_blame_cb_cx	*cb_cx;
	fsl_annotate_opt	 blame_opt;
	fnc_cancel_cb		 cancel_cb;
	const char		*path;
	void			*cancel_cx;
	bool			*complete;
};

struct fnc_blame {
	struct fnc_blame_thread_cx	 thread_cx;
	struct fnc_blame_cb_cx		 cb_cx;
	FILE				*f;	/* Non-annotated copy of file */
	struct fnc_blame_line		*lines;
	off_t				*line_offsets;
	off_t				 filesz;
	fsl_id_t			 origin; /* Tip rid for reverse blame */
	int				 nlines;
	int				 nlimit;    /* Limit depth traversal. */
	pthread_t			 thread_id;
};

CONCAT(STAILQ, _HEAD)(fnc_commit_id_queue, fnc_commit_qid);
struct fnc_commit_qid {
	CONCAT(STAILQ, _ENTRY)(fnc_commit_qid) entry;
	fsl_uuid_str	 id;
};

struct fnc_blame_view_state {
	struct fnc_blame		 blame;
	struct fnc_commit_id_queue	 blamed_commits;
	struct fnc_commit_qid		*blamed_commit;
	struct fnc_commit_artifact	*selected_commit;
	fsl_list			 colours;
	fsl_uuid_str			 commit_id;
	char				*path;
	int				 first_line_onscreen;
	int				 last_line_onscreen;
	int				 selected_line;
	int				 matched_line;
	int				 spin_idx;
	bool				 done;
	bool				 blame_complete;
	bool				 eof;
	bool				 colour;
};

struct fnc_branch {
	char		*name;
	char		*date;
	fsl_uuid_str	 id;
	bool		 private;
	bool		 current;
	bool		 open;
};

struct fnc_branchlist_entry {
	TAILQ_ENTRY(fnc_branchlist_entry) entries;
	struct fnc_branch	*branch;
	int			 idx;
};
TAILQ_HEAD(fnc_branchlist_head, fnc_branchlist_entry);

struct fnc_branch_view_state {
	struct fnc_branchlist_head	 branches;
	struct fnc_branchlist_entry	*first_branch_onscreen;
	struct fnc_branchlist_entry	*last_branch_onscreen;
	struct fnc_branchlist_entry	*matched_branch;
	struct fnc_branchlist_entry	*selected_branch;
	const char			*branch_glob;
	double				 dateline;
	int				 branch_flags;
#define BRANCH_LS_CLOSED_ONLY	0x001  /* Show closed branches only. */
#define BRANCH_LS_OPEN_ONLY	0x002  /* Show open branches only. */
#define BRANCH_LS_OPEN_CLOSED	0x003  /* Show open & closed branches (dflt). */
#define BRANCH_LS_BITMASK	0x003
#define BRANCH_LS_NO_PRIVATE	0x004  /* Show public branches only. */
#define BRANCH_SORT_MTIME	0x008  /* Sort by activity. (default: name) */
#define BRANCH_SORT_STATUS	0x010  /* Sort by open/closed. */
#define BRANCH_SORT_REVERSE	0x020  /* Reverse sort order. */
	int				 nbranches;
	int				 ndisplayed;
	int				 selected;
	int				 when;
	bool				 colour;
	bool				 show_date;
	bool				 show_id;
};

TAILQ_HEAD(view_tailhead, fnc_view);
struct fnc_view {
	TAILQ_ENTRY(fnc_view)	 entries;
	WINDOW			*window;
	PANEL			*panel;
	struct fnc_view		*parent;
	struct fnc_view		*child;
	union {
		struct fnc_diff_view_state	diff;
		struct fnc_tl_view_state	timeline;
		struct fnc_tree_view_state	tree;
		struct fnc_blame_view_state	blame;
		struct fnc_branch_view_state	branch;
	} state;
	enum fnc_view_id	 vid;
	enum fnc_search_state	 search_status;
	enum fnc_search_mvmnt	 searching;
	int			 nlines;
	int			 ncols;
	int			 start_ln;
	int			 start_col;
	int			 lines;	/* Duplicate curses LINES macro. */
	int			 cols;	/* Duplicate curses COLS macro. */
	bool			 focus_child;
	bool			 active; /* Only 1 parent or child at a time. */
	bool			 egress;
	bool			 started_search;
	regex_t			 regex;
	regmatch_t		 regmatch;

	int	(*show)(struct fnc_view *);
	int	(*input)(struct fnc_view **, struct fnc_view *, int);
	int	(*close)(struct fnc_view *);
	int	(*search_init)(struct fnc_view *);
	int	(*search_next)(struct fnc_view *);
};

static volatile sig_atomic_t rec_sigwinch;
static volatile sig_atomic_t rec_sigpipe;
static volatile sig_atomic_t rec_sigcont;

static void		 fnc_show_version(void);
static int		 init_curses(void);
static struct fnc_view	*view_open(int, int, int, int, enum fnc_view_id);
static int		 open_timeline_view(struct fnc_view *, fsl_id_t,
			    const char *);
static int		 view_loop(struct fnc_view *);
static int		 show_timeline_view(struct fnc_view *);
static void		*tl_producer_thread(void *);
static int		 block_main_thread_signals(void);
static int		 build_commits(struct fnc_tl_thread_cx *);
static int		 commit_builder(struct fnc_commit_artifact **, fsl_id_t,
			    fsl_stmt *);
static int		 signal_tl_thread(struct fnc_view *, int);
static int		 draw_commits(struct fnc_view *);
static void		 parse_emailaddr_username(char **);
static int		 formatln(wchar_t **, int *, const char *, int, int);
static int		 multibyte_to_wchar(const char *, wchar_t **, size_t *);
static int		 write_commit_line(struct fnc_view *,
			    struct fnc_commit_artifact *, int);
static int		 view_input(struct fnc_view **, int *,
			    struct fnc_view *, struct view_tailhead *);
static int		 help(struct fnc_view *);
static int		 padpopup(struct fnc_view *, int, int, FILE *,
			    const char *);
static void		 centerprint(WINDOW *, int, int, int, const char *,
			    chtype);
static int		 tl_input_handler(struct fnc_view **, struct fnc_view *,
			    int);
static int		 timeline_scroll_down(struct fnc_view *, int);
static void		 timeline_scroll_up(struct fnc_tl_view_state *, int);
static void		 select_commit(struct fnc_tl_view_state *);
static int		 view_is_parent(struct fnc_view *);
static int		 make_splitscreen(struct fnc_view *);
static int		 make_fullscreen(struct fnc_view *);
static int		 view_split_start_col(int);
static int		 view_search_start(struct fnc_view *);
static int		 tl_search_init(struct fnc_view *);
static int		 tl_search_next(struct fnc_view *);
static bool		 find_commit_match(struct fnc_commit_artifact *,
			    regex_t *);
static int		 init_diff_commit(struct fnc_view **, int,
			    struct fnc_commit_artifact *, struct fnc_view *);
static int		 open_diff_view(struct fnc_view *,
			    struct fnc_commit_artifact *, int, bool, bool, bool,
			    struct fnc_view *, bool,
			    struct fnc_pathlist_head *);
static void		 show_diff_status(struct fnc_view *);
static int		 create_diff(struct fnc_diff_view_state *);
static int		 create_changeset(struct fnc_commit_artifact *);
static int		 write_commit_meta(struct fnc_diff_view_state *);
static int		 wrapline(char *, fsl_size_t ncols_avail,
			    struct fnc_diff_view_state *, off_t *);
static int		 add_line_offset(off_t **, size_t *, off_t);
static int		 diff_commit(fsl_buffer *, struct fnc_commit_artifact *,
			    int, int, int, struct fnc_pathlist_head *);
static int		 diff_checkout(fsl_buffer *, fsl_id_t, int, int, int,
			    struct fnc_pathlist_head *);
static int		 write_diff_meta(fsl_buffer *, const char *,
			    fsl_uuid_str, const char *, fsl_uuid_str, int,
			    enum fsl_ckout_change_e);
static int		 diff_file(fsl_buffer *, fsl_buffer *, const char *,
			    fsl_uuid_str, const char *, enum fsl_ckout_change_e,
			    int, int, bool);
static int		 diff_non_checkin(fsl_buffer *,
			    struct fnc_commit_artifact *, int, int, int);
static int		 diff_file_artifact(fsl_buffer *, fsl_id_t,
			    const fsl_card_F *, fsl_id_t, const fsl_card_F *,
			    fsl_ckout_change_e, int, int, int,
			    enum fnc_diff_type);
static int		 show_diff(struct fnc_view *);
static int		 write_diff(struct fnc_view *, char *);
static int		 match_line(const void *, const void *);
static int		 write_matched_line(int *, const char *, int, int,
			    WINDOW *, regmatch_t *);
static void		 draw_vborder(struct fnc_view *);
static int		 diff_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 set_selected_commit(struct fnc_diff_view_state *,
			    struct commit_entry *);
static int		 diff_search_init(struct fnc_view *);
static int		 diff_search_next(struct fnc_view *);
static int		 view_close(struct fnc_view *);
static int		 map_repo_path(char **);
static bool		 path_is_child(const char *, const char *, size_t);
static int		 path_skip_common_ancestor(char **, const char *,
			    size_t, const char *, size_t);
static bool		 fnc_path_is_root_dir(const char *);
/* static bool		 fnc_path_is_cwd(const char *); */
static int		 fnc_pathlist_insert(struct fnc_pathlist_entry **,
			    struct fnc_pathlist_head *, const char *, void *);
static int		 fnc_path_cmp(const char *, const char *, size_t,
			    size_t);
static void		 fnc_pathlist_free(struct fnc_pathlist_head *);
static int		 browse_commit_tree(struct fnc_view **, int,
			    struct commit_entry *, const char *);
static int		 open_tree_view(struct fnc_view *, const char *,
			    fsl_id_t);
static int		 walk_tree_path(struct fnc_tree_view_state *,
			    struct fnc_repository_tree *,
			    struct fnc_tree_object **, const char *);
static int		 create_repository_tree(struct fnc_repository_tree **,
			    fsl_uuid_str *, fsl_id_t);
static int		 tree_builder(struct fnc_repository_tree *,
			    struct fnc_tree_object **, const char *);
/* static void		 delete_tree_node(struct fnc_tree_entry **, */
/*			    struct fnc_tree_entry *); */
static int		 link_tree_node(struct fnc_repository_tree *,
			    const char *, const char *, fsl_time_t);
static int		 show_tree_view(struct fnc_view *);
static int		 tree_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 blame_tree_entry(struct fnc_view **, int,
			    struct fnc_tree_entry *, struct fnc_parent_trees *,
			    fsl_uuid_str);
static int		 tree_search_init(struct fnc_view *);
static int		 tree_search_next(struct fnc_view *);
static int		 tree_entry_path(char **, struct fnc_parent_trees *,
			    struct fnc_tree_entry *);
static int		 draw_tree(struct fnc_view *, const char *);
static int		 timeline_tree_entry(struct fnc_view **, int,
			    struct fnc_tree_view_state *);
static void		 tree_scroll_up(struct fnc_tree_view_state *, int);
static void		 tree_scroll_down(struct fnc_tree_view_state *, int);
static int		 visit_subtree(struct fnc_tree_view_state *,
			    struct fnc_tree_object *);
static int		 tree_entry_get_symlink_target(char **,
			    struct fnc_tree_entry *);
static int		 match_tree_entry(struct fnc_tree_entry *, regex_t *);
static void		 fnc_object_tree_close(struct fnc_tree_object *);
static void		 fnc_close_repository_tree(struct fnc_repository_tree *);
static int		 open_blame_view(struct fnc_view *, char *,
			    fsl_uuid_str, fsl_id_t, int);
static int		 run_blame(struct fnc_view *);
static int		 fnc_dump_buffer_to_file(off_t *, int *, off_t **,
			    FILE *, fsl_buffer *);
static int		 show_blame_view(struct fnc_view *);
static void		*blame_thread(void *);
static int		 blame_cb(void *, fsl_annotate_opt const * const,
			    fsl_annotate_step const * const);
static int		 draw_blame(struct fnc_view *);
static int		 blame_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 blame_search_init(struct fnc_view *);
static int		 blame_search_next(struct fnc_view *);
static fsl_uuid_cstr	 get_selected_commit_id(struct fnc_blame_line *,
			    int, int, int);
static int		 fnc_commit_qid_alloc(struct fnc_commit_qid **,
			    fsl_uuid_cstr);
static int		 close_blame_view(struct fnc_view *);
static int		 stop_blame(struct fnc_blame *);
static int		 cancel_blame(void *);
static void		 fnc_commit_qid_free(struct fnc_commit_qid *);
static int		 fnc_load_branches(struct fnc_branch_view_state *);
static int		 create_tmp_branchlist_table(void);
static int		 alloc_branch(struct fnc_branch **, const char *,
			    double, bool, bool, bool);
static int		 fnc_branchlist_insert(struct fnc_branchlist_entry **,
			    struct fnc_branchlist_head *, struct fnc_branch *);
static int		 open_branch_view(struct fnc_view *, int, const char *,
			    double, int);
static int		 show_branch_view(struct fnc_view *);
static int		 branch_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 tl_branch_entry(struct fnc_view **, int,
			    struct fnc_branchlist_entry *);
static int		 browse_branch_tree(struct fnc_view **, int,
			    struct fnc_branchlist_entry *);
static void		 branch_scroll_up(struct fnc_branch_view_state *, int);
static void		 branch_scroll_down(struct fnc_branch_view_state *,
			    int);
static int		 branch_search_next(struct fnc_view *);
static int		 branch_search_init(struct fnc_view *);
static int		 match_branchlist_entry(struct fnc_branchlist_entry *,
			    regex_t *);
static int		 close_branch_view(struct fnc_view *);
static void		 fnc_free_branches(struct fnc_branch_view_state *);
static void		 fnc_branch_close(struct fnc_branch *);
static void		 view_set_child(struct fnc_view *, struct fnc_view *);
static int		 view_close_child(struct fnc_view *);
static int		 close_tree_view(struct fnc_view *);
static int		 close_timeline_view(struct fnc_view *);
static int		 close_diff_view(struct fnc_view *);
static int		 view_resize(struct fnc_view *);
static int		 screen_is_split(struct fnc_view *);
static bool		 screen_is_shared(struct fnc_view *);
static void		 fnc_resizeterm(void);
static int		 join_tl_thread(struct fnc_tl_view_state *);
static void		 fnc_free_commits(struct commit_queue *);
static void		 fnc_commit_artifact_close(struct fnc_commit_artifact*);
static int		 fsl_list_object_free(void *, void *);
static void		 sigwinch_handler(int);
static void		 sigpipe_handler(int);
static void		 sigcont_handler(int);
static int		 strtonumcheck(int *, const char *, const int,
			    const int);
static int		 fnc_date_to_mtime(double *, const char *, int);
static char		*fnc_strsep (char **, const char *);
#ifdef __linux__
static size_t		 fnc_strlcat(char *, const char *, size_t);
static size_t		 fnc_strlcpy(char *, const char *, size_t);
#endif
static int		 set_colours(fsl_list *, enum fnc_view_id vid);
static int		 match_colour(const void *, const void *);
static bool		 fnc_home(struct fnc_view *);
static struct fnc_colour	*get_colour(fsl_list *, int);
static struct fnc_tree_entry	*get_tree_entry(struct fnc_tree_object *,
				    int);
static struct fnc_tree_entry	*find_tree_entry(struct fnc_tree_object *,
				    const char *, size_t);

int
main(int argc, const char **argv)
{
	fcli_command	*cmd = NULL;
	char		*path = NULL;
	int		 rc = 0;

	fnc_init.filter_types =
	    (struct artifact_types *)fsl_malloc(sizeof(struct artifact_types));
	fnc_init.filter_types->values = fsl_malloc(sizeof(char *));
	fnc_init.filter_types->nitems = 0;

	if (!setlocale(LC_CTYPE, ""))
		fsl_fprintf(stderr, "[!] Warning: Can't set locale.\n");

	fnc_init.cmdarg = argv[1];	/* Which cmd to show usage if needed. */
	fcli.clientFlags.verbose = 2;	/* Verbose error reporting. */
	fcli.cliFlags = fnc_init.cliflags_global;
	fcli.appHelp = &fnc_init.fnc_help;
	rc = fcli_setup(argc, argv);
	if (rc)
		goto end;

	if (fnc_init.vflag) {
		fnc_show_version();
		goto end;
	} else if (fnc_init.hflag)
		usage();
		/* NOT REACHED */

	rc = fcli_fingerprint_check(true);
	if (rc)
		goto end;

	if (argc == 1)
		cmd = &fnc_init.cmd_args[FNC_VIEW_TIMELINE];
	else {
		rc = fcli_dispatch_commands(fnc_init.cmd_args, false);
		if (rc == FSL_RC_NOT_FOUND && argc == 2) {
			/*
			 * Check if user entered fnc path/in/repo; if valid path
			 * is found, assume fnc timeline path/in/repo was meant.
			 */
			rc = map_repo_path(&path);
			if (rc == FSL_RC_NOT_FOUND || !path) {
				rc = RC(rc,
				    "'%s' is not a valid command or path",
				    argv[1]);
				fnc_init.err = rc;
				usage();
				/* NOT REACHED */
			} else if (rc)
				goto end;
			cmd = &fnc_init.cmd_args[FNC_VIEW_TIMELINE];
			fnc_init.path = path;
			fcli_err_reset(); /* cmd_timeline::fcli_process_flags */
		} else if (rc)
			goto end;
	}

	if ((rc = fcli_has_unused_args(false))) {
		fnc_init.err = rc;
		usage();
		/* NOT REACHED */
	}

	if (!fsl_cx_db_repo(fcli_cx())) {
		rc = RC(FSL_RC_MISUSE, "%s", "repository database required");
		goto end;
	}

	if (cmd != NULL)
		rc = cmd->f(cmd);
end:
	fsl_free(path);
	endwin();
	if (rc) {
		if (rc == FCLI_RC_HELP)
			rc = 0;
		else if (rc == FSL_RC_BREAK) {
			fsl_cx *f = fcli_cx();
			const char *errstr;
			fsl_error_get(&f->error, &errstr, NULL);
			fsl_fprintf(stdout, "%s", errstr);
			fcli_err_reset();  /* For fcli_end_of_main() */
			rc = 0;
		}
		else
			fsl_fprintf(stderr, "%s: %s %d\n", fcli_progname(),
			    fsl_rc_cstr(rc), rc);
	}
	putchar('\n');
	return fcli_end_of_main(rc);
}

static int
cmd_timeline(fcli_command const *argv)
{
	struct fnc_view	*v;
	fsl_cx		*f = fcli_cx();
	fsl_id_t	 rid = -1;
	char		*path = NULL;
	int		 rc = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	if (fnc_init.nrecords.zlimit)
		if ((rc = strtonumcheck(&fnc_init.nrecords.limit,
		    fnc_init.nrecords.zlimit, INT_MIN, INT_MAX)))
			return rc;

	if (fnc_init.sym != NULL) {
		rc = fsl_sym_to_rid(f, fnc_init.sym, FSL_SATYPE_CHECKIN, &rid);
		if (rc || rid < 0)
			return RC(FSL_RC_TYPE,
			    "artifact [%s] not resolvable to a commit",
			    fnc_init.sym);
	}

	if (fnc_init.path)
		path = fsl_strdup(fnc_init.path);
	else
		rc = map_repo_path(&path);
	if (!rc)
		rc = init_curses();
	if (rc)
		goto end;
	v = view_open(0, 0, 0, 0, FNC_VIEW_TIMELINE);
	if (v == NULL) {
		RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}
	rc = open_timeline_view(v, rid, path);
	if (!rc)
		rc = view_loop(v);
end:
	fsl_free(path);
	return rc;
}

/*
 * Look for an in-repository path in **argv. If found, canonicalise it as an
 * absolute path relative to the repository root (e.g., /ckoutdir/found/path),
 * and assign to a dynamically allocated string in *requested_path, which the
 * caller must dispose of with fsl_free or free(3).
 */
static int
map_repo_path(char **requested_path)
{
	fsl_cx		*const f = fcli_cx();
	fsl_buffer	 buf = fsl_buffer_empty;
	char		*canonpath = NULL, *ckoutdir = NULL, *path = NULL;
	const char	*ckoutdir0 = NULL;
	fsl_size_t	 len;
	int		 rc = 0;
	bool		 root;

	*requested_path = NULL;

	/* If no path argument is supplied, default to repository root. */
	if (!fcli_next_arg(false)) {
		*requested_path = fsl_strdup("/");
		if (*requested_path == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		return rc;
	}

	canonpath = fsl_strdup(fcli_next_arg(true));
	if (canonpath == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}

	/*
	 * If no checkout (e.g., 'fnc timeline -R') copy the path verbatim to
	 * check its validity against a deck of F cards in open_timeline_view().
	 */
	ckoutdir0 = fsl_cx_ckout_dir_name(f, &len);
	if (!ckoutdir0) {
		path = fsl_strdup(canonpath);
		goto end;
	}

	path = realpath(canonpath, NULL);
	if (path == NULL && (errno == ENOENT || errno == ENOTDIR)) {
		/* Path is not on disk, assume it is relative to repo root. */
		rc = fsl_file_canonical_name2(ckoutdir0, canonpath, &buf, NULL);
		if (rc) {
			rc = RC(rc, "%s", "fsl_file_canonical_name2");
			goto end;
		}
		fsl_free(path);
		path = realpath(fsl_buffer_cstr(&buf), NULL);
		if (path) {
			/* Confirmed path is relative to repository root. */
			fsl_free(path);
			path = fsl_strdup(canonpath);
			if (path == NULL)
				rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		} else {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_NOT_FOUND),
			    "'%s' not found in tree", canonpath);
			*requested_path = fsl_strdup(canonpath);
		}
		goto end;
	}
	fsl_free(path);
	/*
	 * Use the cwd as the virtual root to canonicalise the supplied path if
	 * it is either: (a) relative; or (b) the root of the current checkout.
	 * Otherwise, use the root of the current checkout.
	 */
	rc = fsl_cx_getcwd(f, &buf);
	if (rc)
		goto end;
	ckoutdir = fsl_mprintf("%.*s", len - 1, ckoutdir0);
	root = fsl_strcmp(ckoutdir, fsl_buffer_cstr(&buf)) == 0;
	fsl_buffer_reuse(&buf);
	rc = fsl_ckout_filename_check(f, (canonpath[0] == '.' || !root) ?
	    true : false, canonpath, &buf);
	if (rc)
		goto end;
	fsl_free(canonpath);
	canonpath = fsl_strdup(fsl_buffer_str(&buf));

	if (canonpath[0] == '\0') {
		path = fsl_strdup(canonpath);
		if (path == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else {
		fsl_buffer_reuse(&buf);
		rc = fsl_file_canonical_name2(f->ckout.dir, canonpath, &buf,
		    false);
		if (rc)
			goto end;
		path = fsl_strdup(fsl_buffer_str(&buf));
		if (path == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		if (access(path, F_OK) != 0) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
			    "path does not exist or inaccessible [%s]", path);
			goto end;
		}
		/*
		 * Now we have an absolute path, check again if it's the ckout
		 * dir; if so, clear it to signal an open_timeline_view() check.
		 */
		len = fsl_strlen(path);
		if (!fsl_strcmp(path, f->ckout.dir)) {
			fsl_free(path);
			path = fsl_strdup("");
			if (path == NULL) {
				rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
				goto end;
			}
		} else if (len > f->ckout.dirLen && path_is_child(path,
		    f->ckout.dir, f->ckout.dirLen)) {
			char *child;
			/*
			 * Matched on-disk path within the repository; strip
			 * common prefix with repository root path.
			 */
			rc = path_skip_common_ancestor(&child, f->ckout.dir,
			    f->ckout.dirLen, path, len);
			if (rc)
				goto end;
			fsl_free(path);
			path = child;
		} else {
			/*
			 * Matched on-disk path outside the repository; treat
			 * as relative to repo root. (Though this should fail.)
			 */
			fsl_free(path);
			path = canonpath;
			canonpath = NULL;
		}
	}

	/* Trim trailing slash if it exists. */
	if (path[fsl_strlen(path) - 1] == '/')
		path[fsl_strlen(path) - 1] = '\0';

end:
	fsl_buffer_clear(&buf);
	fsl_free(canonpath);
	fsl_free(ckoutdir);
	if (rc)
		fsl_free(path);
	else {
		/* Make path absolute from repository root. */
		if (path[0] != '/' && (path[0] != '.' && path[1] != '/')) {
			char *abspath;
			if ((abspath = fsl_mprintf("/%s", path)) == NULL) {
				rc = RC(FSL_RC_ERROR, "%s", "fsl_mprintf");
				goto end;
			}
			fsl_free(path);
			path = abspath;
		}

		*requested_path = path;
	}
	return rc;
}

static bool
path_is_child(const char *child, const char *parent, size_t parentlen)
{
	if (parentlen == 0 || fnc_path_is_root_dir(parent))
		return true;

	if (fsl_strncmp(parent, child, parentlen) != 0)
		return false;
	if (child[parentlen - 1 /* Trailing slash */] != '/')
		return false;

	return true;
}

/*
 * As a special case, due to fsl_ckout_filename_check() resolving the current
 * checkout directory to ".", this function returns true for ".". For this
 * reason, when path is intended to be the current working directory for any
 * directory other than the repository root, callers must ensure path is either
 * absolute or relative to the respository root--not ".".
 */
static bool
fnc_path_is_root_dir(const char *path)
{
	while (*path == '/' || *path == '.')
		++path;
	return (*path == '\0');
}

static int
path_skip_common_ancestor(char **child, const char *parent_abspath,
    size_t parentlen, const char *abspath, size_t len)
{
	size_t	bufsz;
	int	rc = 0;

	*child = NULL;

	if (parentlen >= len)
		return RC(FSL_RC_RANGE, "invalid path [%s]", abspath);
	if (fsl_strncmp(parent_abspath, abspath, parentlen) != 0)
		return RC(FSL_RC_TYPE, "invalid path [%s]", abspath);
	if (!fnc_path_is_root_dir(parent_abspath) &&
	    abspath[parentlen - 1 /* Trailing slash */] != '/')
		return RC(FSL_RC_TYPE, "invalid path [%s]", abspath);
	while (abspath[parentlen] == '/')
		++abspath;
	bufsz = len - parentlen + 1;
	*child = fsl_malloc(bufsz);
	if (*child == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	if (strlcpy(*child, abspath + parentlen, bufsz) >= bufsz) {
		rc = RC(FSL_RC_RANGE, "%s", "strlcpy");
		fsl_free(*child);
		*child = NULL;
	}
	return rc;
}

#if 0
static bool
fnc_path_is_cwd(const char *path)
{
	return (path[0] == '.' && path[1] == '\0');
}
#endif

static int
init_curses(void)
{
	initscr();
	cbreak();
	noecho();
	nonl();
	intrflush(stdscr, FALSE);
	keypad(stdscr, TRUE);
	curs_set(0);
	set_escdelay(0);  /* ESC should return immediately. */
#ifndef __linux__
	typeahead(-1);	/* Don't disrupt screen update operations. */
#endif

	if (!fnc_init.nocolour && has_colors()) {
		start_color();
		use_default_colors();
	}

	if (sigaction(SIGPIPE, &(struct sigaction){{sigpipe_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "sigaction(SIGPIPE)");
	if (sigaction(SIGWINCH, &(struct sigaction){{sigwinch_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "sigaction(SIGWINCH)");
	if (sigaction(SIGCONT, &(struct sigaction){{sigcont_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "sigaction(SIGCONT)");

	return 0;
}

static struct fnc_view *
view_open(int nlines, int ncols, int start_ln, int start_col,
    enum fnc_view_id vid)
{
	struct fnc_view *view = calloc(1, sizeof(*view));

	if (view == NULL)
		return NULL;

	view->vid = vid;
	view->lines = LINES;
	view->cols = COLS;
	view->nlines = nlines ? nlines : LINES - start_ln;
	view->ncols = ncols ? ncols : COLS - start_col;
	view->start_ln = start_ln;
	view->start_col = start_col;
	view->window = newwin(nlines, ncols, start_ln, start_col);
	if (view->window == NULL) {
		view_close(view);
		return NULL;
	}
	view->panel = new_panel(view->window);
	if (view->panel == NULL || set_panel_userptr(view->panel, view) != OK) {
		view_close(view);
		return NULL;
	}

	keypad(view->window, TRUE);
	return view;
}

static int
open_timeline_view(struct fnc_view *view, fsl_id_t rid, const char *path)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	fsl_cx				*f = fcli_cx();
	fsl_db				*db = fsl_cx_db_repo(f);
	fsl_buffer			 sql = fsl_buffer_empty;
	char				*startdate = NULL;
	fsl_id_t			 idtag = 0;
	int				 idx, rc = 0;

	if (path != s->path) {
		fsl_free(s->path);
		s->path = fsl_strdup(path);
		if (s->path == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	}

	/*
	 * TODO: See about opening this API.
	 * If a path has been supplied, create a table of all path's
	 * ancestors and add "AND blob.rid IN fsl_computed_ancestors" to query.
	 */
	/* if (path[1]) { */
	/*	rc = fsl_compute_ancestors(db, rid, 0, 0); */
	/*	if (rc) */
	/*		return RC(FSL_RC_DB, "%s", "fsl_compute_ancestors"); */
	/* } */
	s->thread_cx.q = NULL;
	/* s->selected_idx = 0; */	/* Unnecessary? */

	TAILQ_INIT(&s->commits.head);
	s->commits.ncommits = 0;

	if (rid != -1)
		startdate = fsl_mprintf("(SELECT mtime FROM event "
		    "WHERE objid=%d)", rid);
	else
		fsl_ckout_version_info(f, NULL, &s->curr_ckout_uuid);

	/*
	 * In 'fnc timeline -R repo.fossil path' case, check that path is a
	 * valid repository path in the repository tree as at either the
	 * latest check-in or the specified commit.
	 */
	if (s->curr_ckout_uuid == NULL && path[1]) {
		fsl_deck d = fsl_deck_empty;
		bool ispath = false;
		rc = fsl_deck_load_sym(f, &d, fnc_init.sym ? fnc_init.sym :
		    "tip", FSL_SATYPE_CHECKIN);
		fsl_deck_F_rewind(&d);
		if (fsl_deck_F_search(&d, path + 1 /* Slash */) == NULL) {
			const fsl_card_F *cf;
			fsl_deck_F_next(&d, &cf);
			do {
				fsl_deck_F_next(&d, &cf);
				if (cf && !fsl_strncmp(path + 1 /* Slash */,
				    cf->name, fsl_strlen(path) - 1)) {
					ispath = true;
					break;
				}
			} while (cf);
		} else
			ispath = true;
		fsl_deck_finalize(&d);
		if (!ispath)
			return RC(FSL_RC_NOT_FOUND, "'%s' invalid path in [%s]",
			    path + 1, fnc_init.sym ? fnc_init.sym : "tip");
	}

	if ((rc = pthread_cond_init(&s->thread_cx.commit_consumer, NULL))) {
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_init");
		goto end;
	}
	if ((rc = pthread_cond_init(&s->thread_cx.commit_producer, NULL))) {
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_init");
		goto end;
	}

	fsl_buffer_appendf(&sql, "SELECT "
            /* 0 */"uuid, "
	    /* 1 */"datetime(event.mtime%s), "
	    /* 2 */"coalesce(euser, user), "
	    /* 3 */"rid AS rid, "
	    /* 4 */"event.type AS eventtype, "
	    /* 5 */"(SELECT group_concat(substr(tagname,5), ',') "
	    "FROM tag, tagxref WHERE tagname GLOB 'sym-*' "
	    "AND tag.tagid=tagxref.tagid AND tagxref.rid=blob.rid "
	    "AND tagxref.tagtype > 0) as tags, "
	    /*6*/"coalesce(ecomment, comment) AS comment FROM event JOIN blob "
	    "WHERE blob.rid=event.objid", fnc_init.utc ? "" : ", 'localtime'");

	if (fnc_init.filter_types->nitems) {
		fsl_buffer_appendf(&sql, " AND (");
		for (idx = 0; idx < fnc_init.filter_types->nitems; ++idx) {
			fsl_buffer_appendf(&sql, " eventtype=%Q%s",
			    fnc_init.filter_types->values[idx], (idx + 1) <
			    fnc_init.filter_types->nitems ? " OR " : ")");
			/* This produces a double-free? */
			/* fsl_free((char *)fnc_init.filter_types->values[idx]); */
			fnc_init.filter_types->values[idx] = NULL;
		}
		fsl_free(fnc_init.filter_types->values);
		fsl_free(fnc_init.filter_types);
	}

	if (fnc_init.filter_branch) {
		idtag = fsl_db_g_id(db, 0,
                    "SELECT tagid FROM tag WHERE tagname='sym-%q'",
                    fnc_init.filter_branch);
		if (idtag > 0)
			fsl_buffer_appendf(&sql,
                             " AND EXISTS(SELECT 1 FROM tagxref"
                             " WHERE tagid=%"FSL_ID_T_PFMT
                             " AND tagtype > 0 AND rid=blob.rid)", idtag);
		else {
			rc = RC(FSL_RC_NOT_FOUND, "Invalid branch name [%s]",
			    fnc_init.filter_branch);
			goto end;
		}
	}

	if (fnc_init.filter_tag) {
		idtag = fsl_db_g_id(db, 0,
                    "SELECT tagid FROM tag WHERE tagname GLOB 'sym-%q'",
                    fnc_init.filter_tag);
                if (idtag == 0)
			idtag = fsl_db_g_id(db, 0,
			    "SELECT tagid FROM tag WHERE tagname='%q'",
			    fnc_init.filter_tag);
		if (idtag > 0)
			fsl_buffer_appendf(&sql,
                             " AND EXISTS(SELECT 1 FROM tagxref"
                             " WHERE tagid=%"FSL_ID_T_PFMT
                             " AND tagtype > 0 AND rid=blob.rid)", idtag);
		else {
			rc = RC(FSL_RC_NOT_FOUND, "Invalid tag [%s]",
			    fnc_init.filter_tag);
			goto end;
		}
	}

	if (fnc_init.filter_user)
		if ((rc = fsl_buffer_appendf(&sql,
                    " AND coalesce(euser, user) GLOB lower('*%q*')",
                    fnc_init.filter_user)))
		goto end;

	if (startdate) {
		fsl_buffer_appendf(&sql, " AND event.mtime <= %s", startdate);
		fsl_free(startdate);
	}

	/*
	 * If path is not root ("/"), a versioned path in the repository has
	 * been requested, only retrieve commits involving path.
	 */
	if (path[1]) {
		fsl_buffer_appendf(&sql,
		    " AND EXISTS(SELECT 1 FROM mlink"
		    " WHERE mlink.mid = event.objid"
		    " AND mlink.fnid IN ");
		if (fsl_cx_is_case_sensitive(f)) {
			fsl_buffer_appendf(&sql,
			    "(SELECT fnid FROM filename"
			    " WHERE name = %Q OR name GLOB '%q/*')",
			    path + 1, path + 1);  /* Skip prepended slash. */
		} else {
			fsl_buffer_appendf(&sql,
			    "(SELECT fnid FROM filename"
			    " WHERE name = %Q COLLATE nocase"
			    " OR lower(name) GLOB lower('%q/*'))",
			    path + 1, path + 1);  /* Skip prepended slash. */
		}
		fsl_buffer_append(&sql, ")", 1);
	}

	fsl_buffer_appendf(&sql, " ORDER BY event.mtime DESC");

	if (fnc_init.nrecords.limit > 0)
		fsl_buffer_appendf(&sql, " LIMIT %d", fnc_init.nrecords.limit);

	view->show = show_timeline_view;
	view->input = tl_input_handler;
	view->close = close_timeline_view;
	view->search_init = tl_search_init;
	view->search_next = tl_search_next;

	s->thread_cx.q = fsl_stmt_malloc();
	rc = fsl_db_prepare(db, s->thread_cx.q, "%b", &sql);
	if (rc) {
		rc = RC(rc, "%s", "fsl_db_prepare");
		goto end;
	}
	rc = fsl_stmt_step(s->thread_cx.q);
	if (rc) {
		switch (rc) {
		case FSL_RC_STEP_ROW:
			rc = 0;
			break;
		case FSL_RC_STEP_ERROR:
			rc = RC(rc, "%s", "fsl_stmt_step");
			goto end;
		case FSL_RC_STEP_DONE:
			rc = RC(FSL_RC_BREAK, "%s", "no matching records");
			goto end;
		}
	}

	s->colour = !fnc_init.nocolour && has_colors();
	s->thread_cx.rc = 0;
	s->thread_cx.db = db;
	s->thread_cx.spin_idx = 0;
	s->thread_cx.ncommits_needed = view->nlines - 1;
	s->thread_cx.commits = &s->commits;
	s->thread_cx.timeline_end = false;
	s->thread_cx.quit = &s->quit;
	s->thread_cx.first_commit_onscreen = &s->first_commit_onscreen;
	s->thread_cx.selected_commit = &s->selected_commit;
	s->thread_cx.searching = &view->searching;
	s->thread_cx.search_status = &view->search_status;
	s->thread_cx.regex = &view->regex;
	s->thread_cx.path = s->path;

	if (s->colour)
		set_colours(&s->colours, FNC_VIEW_TIMELINE);
end:
	fsl_buffer_clear(&sql);
	if (rc) {
		close_timeline_view(view);
		if (db->error.code)
			rc = fsl_cx_uplift_db_error(f, db);
	}
	return rc;
}

static int
view_loop(struct fnc_view *view)
{
	struct view_tailhead	 views;
	struct fnc_view		*new_view;
	int			 done = 0, err = 0, rc = 0;

	if ((rc = pthread_mutex_lock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	TAILQ_INIT(&views);
	TAILQ_INSERT_HEAD(&views, view, entries);

	view->active = true;
	rc = view->show(view);
	if (rc)
		return rc;

	while (!TAILQ_EMPTY(&views) && !done && !rec_sigpipe) {
		rc = view_input(&new_view, &done, view, &views);
		if (rc)
			break;
		if (view->egress) {
			struct fnc_view *v, *prev = NULL;

			if (view_is_parent(view))
				prev = TAILQ_PREV(view, view_tailhead, entries);
			else if (view->parent)
				prev = view->parent;

			if (view->parent) {
				view->parent->child = NULL;
				view->parent->focus_child = false;
			} else
				TAILQ_REMOVE(&views, view, entries);

			rc = view_close(view);
			if (rc)
				goto end;

			view = NULL;
			TAILQ_FOREACH(v, &views, entries) {
				if (v->active)
					break;
			}
			if (view == NULL && new_view == NULL) {
				/* No view is active; try to pick one. */
				if (prev)
					view = prev;
				else if (!TAILQ_EMPTY(&views))
					view = TAILQ_LAST(&views,
					    view_tailhead);
				if (view) {
					if (view->focus_child) {
						view->child->active = true;
						view = view->child;
					} else
						view->active = true;
				}
			}
		}
		if (new_view) {
			struct fnc_view *v, *t;
			/* Allow only one parent view per type. */
			TAILQ_FOREACH_SAFE(v, &views, entries, t) {
				if (v->vid != new_view->vid)
					continue;
				TAILQ_REMOVE(&views, v, entries);
				rc = view_close(v);
				if (rc)
					goto end;
				break;
			}
			TAILQ_INSERT_TAIL(&views, new_view, entries);
			view = new_view;
		}
		if (view) {
			if (view_is_parent(view)) {
				if (view->child && view->child->active)
					view = view->child;
			} else {
				if (view->parent && view->parent->active)
					view = view->parent;
			}
			show_panel(view->panel);
			if (view->child && screen_is_split(view->child))
				show_panel(view->child->panel);
			if (view->parent && screen_is_split(view)) {
				rc = view->parent->show(view->parent);
				if (rc)
					goto end;
			}
			rc = view->show(view);
			if (rc)
				goto end;
			if (view->child) {
				rc = view->child->show(view->child);
#ifdef __linux__
				wnoutrefresh(view->child->window);
#endif
				if (rc)
					goto end;
			}
#ifdef __linux__
			wnoutrefresh(view->window);
#else
			update_panels();
#endif
			doupdate();
		}
	}
end:
	while (!TAILQ_EMPTY(&views)) {
		view = TAILQ_FIRST(&views);
		TAILQ_REMOVE(&views, view, entries);
		view_close(view);
	}

	if ((err = pthread_mutex_unlock(&fnc_mutex)) && !rc)
		rc = RC(fsl_errno_to_rc(err, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");

	return rc;
}

static int
show_timeline_view(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	int				 rc = 0;

	if (!s->thread_id) {
		rc = pthread_create(&s->thread_id, NULL, tl_producer_thread,
		    &s->thread_cx);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_create");
		if (s->thread_cx.ncommits_needed > 0) {
			rc = signal_tl_thread(view, 1);
			if (rc)
				return rc;
		}
	}

	return draw_commits(view);
}

static void *
tl_producer_thread(void *state)
{
	struct fnc_tl_thread_cx	*cx = state;
	int			 rc;
	bool			 done = false;

	rc = block_main_thread_signals();
	if (rc)
		return (void *)(intptr_t)rc;

	while (!done && !rc && !rec_sigpipe) {
		switch (rc = build_commits(cx)) {
		case FSL_RC_STEP_DONE:
			done = true;
			/* FALL THROUGH */
		case FSL_RC_STEP_ROW:
			rc = 0;
			/* FALL THROUGH */
		default:
			if (rc) {
				cx->rc = rc;
				return (void *)(intptr_t)rc;
			}
			else if (cx->ncommits_needed > 0)
				cx->ncommits_needed--;
			break;
		}

		if ((rc = pthread_mutex_lock(&fnc_mutex))) {
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
			break;
		} else if (*cx->first_commit_onscreen == NULL) {
			*cx->first_commit_onscreen =
			    TAILQ_FIRST(&cx->commits->head);
			*cx->selected_commit = *cx->first_commit_onscreen;
		} else if (*cx->quit)
			done = true;

		if ((rc = pthread_cond_signal(&cx->commit_producer))) {
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_cond_signal");
			pthread_mutex_unlock(&fnc_mutex);
			break;
		}

		if (done)
			cx->ncommits_needed = 0;
		else if (cx->ncommits_needed == 0) {
			if ((rc = pthread_cond_wait(&cx->commit_consumer,
			    &fnc_mutex)))
				rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
				    "%s", "pthread_cond_wait");
			if (*cx->quit)
				done = true;
		}

		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
	}

	cx->timeline_end = true;
	return (void *)(intptr_t)rc;
}

static int
block_main_thread_signals(void)
{
	sigset_t	 set;

	if (sigemptyset(&set) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigemptyset");

	/* Bespoke signal handlers for SIGWINCH and SIGCONT. */
	if (sigaddset(&set, SIGWINCH) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigaddset");
	if (sigaddset(&set, SIGCONT) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigaddset");

	/* ncurses handles SIGTSTP. */
	if (sigaddset(&set, SIGTSTP) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigaddset");

	if (pthread_sigmask(SIG_BLOCK, &set, NULL))
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "pthread_sigmask");

	return 0;
}

static int
build_commits(struct fnc_tl_thread_cx *cx)
{
	int		 rc = 0;

	if (cx->tree_open) {
		/*
		 * XXX If a tree has been opened with the 't' key binding, the
		 * commit builder statement needs to be reset otherwise one of
		 * the SQLite3 APIs down the fsl_stmt_step() call stack fails,
		 * irrespective of whether fsl_db_prepare_cached() is called.
		 */
		fsl_size_t loaded = cx->q->rowCount;
		cx->tree_open = false;
		rc = fsl_stmt_reset(cx->q);
		if (rc)
			return RC(rc, "%s", "fsl_stmt_reset");
		while (loaded--)
			if ((rc = fsl_stmt_step(cx->q)) != FSL_RC_STEP_ROW)
				return RC(rc, "%s", "fsl_stmt_step");
	}
	/*
	 * Step through the given SQL query, passing each row to the commit
	 * builder to build commits for the timeline.
	 */
	do {
		struct fnc_commit_artifact	*commit = NULL;
		struct commit_entry		*dup_entry, *entry;

		rc = commit_builder(&commit, 0, cx->q);
		if (rc)
			return RC(rc, "%s", "commit_builder");
		/*
		 * TODO: Find out why, without this, fnc reads and displays
		 * the first (i.e., latest) commit twice. This hack checks to
		 * see if the current row returned a UUID matching the last
		 * commit added to the list to avoid adding a duplicate entry.
		 */
		dup_entry = TAILQ_FIRST(&cx->commits->head);
		if (cx->commits->ncommits == 1 &&
		    !fsl_strcmp(dup_entry->commit->uuid, commit->uuid)) {
			fnc_commit_artifact_close(commit);
			cx->ncommits_needed++;
			continue;
		}

		entry = fsl_malloc(sizeof(*entry));
		if (entry == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_malloc");

		entry->commit = commit;

		rc = pthread_mutex_lock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");

		entry->idx = cx->commits->ncommits;
		TAILQ_INSERT_TAIL(&cx->commits->head, entry, entries);
		cx->commits->ncommits++;

		if (!cx->endjmp && *cx->searching == SEARCH_FORWARD &&
		    *cx->search_status == SEARCH_WAITING) {
			if (find_commit_match(commit, cx->regex))
				*cx->search_status = SEARCH_CONTINUE;
		}

		rc = pthread_mutex_unlock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");

	} while ((rc = fsl_stmt_step(cx->q)) == FSL_RC_STEP_ROW
	    && *cx->searching == SEARCH_FORWARD
	    && *cx->search_status == SEARCH_WAITING);

	return rc;
}

/*
 * Given prepared SQL statement q _XOR_ record ID rid, allocate and build the
 * corresponding commit artifact from the result set. The commit must
 * eventually be disposed of with fnc_commit_artifact_close().
 */
static int
commit_builder(struct fnc_commit_artifact **ptr, fsl_id_t rid, fsl_stmt *q)
{
	fsl_cx				*f = fcli_cx();
	fsl_db				*db = fsl_needs_repo(f);
	struct fnc_commit_artifact	*commit = NULL;
	fsl_buffer			 buf = fsl_buffer_empty;
	const char			*comment, *prefix, *type;
	int				 rc = 0;
	enum fnc_diff_type		 diff_type = FNC_DIFF_WIKI;

	if (rid) {
		rc = fsl_db_prepare(db, q, "SELECT "
		    /* 0 */"uuid, "
		    /* 1 */"datetime(event.mtime%s), "
		    /* 2 */"coalesce(euser, user), "
		    /* 3 */"rid AS rid, "
		    /* 4 */"event.type AS eventtype, "
		    /* 5 */"(SELECT group_concat(substr(tagname,5), ',') "
		    "FROM tag, tagxref WHERE tagname GLOB 'sym-*' "
		    "AND tag.tagid=tagxref.tagid AND tagxref.rid=blob.rid "
		    "AND tagxref.tagtype > 0) as tags, "
		    /*6*/"coalesce(ecomment, comment) AS comment "
		    "FROM event JOIN blob WHERE blob.rid=%d AND event.objid=%d",
		    fnc_init.utc ? "" : ", 'localtime'", rid, rid);
		if (rc)
			return RC(FSL_RC_DB, "%s", "fsl_db_prepare");
		fsl_stmt_step(q);
	}

	type = fsl_stmt_g_text(q, 4, NULL);
	comment = fsl_stmt_g_text(q, 6, NULL);
	prefix = NULL;

	switch (*type) {
	case 'c':
		type = "checkin";
		diff_type = FNC_DIFF_COMMIT;
		break;
	case 'w':
		type = "wiki";
		if (comment) {
			switch (*comment) {
			case '+':
				prefix = "Added: ";
				++comment;
				break;
			case '-':
				prefix = "Deleted: ";
				++comment;
				break;
			case ':':
				prefix = "Edited: ";
				++comment;
				break;
			default:
				break;
			}
			if (prefix)
				rc = fsl_buffer_append(&buf, prefix, -1);
		}
		break;
	case 'g':
		type = "tag";
		break;
	case 'e':
		type = "technote";
		break;
	case 't':
		type = "ticket";
		break;
	case 'f':
		type = "forum";
		break;
	};
	if (!rc && comment)
		rc = fsl_buffer_append(&buf, comment, -1);
	if (rc) {
		rc = RC(rc, "%s", "fsl_buffer_append");
		goto end;
	}

	commit = calloc(1, sizeof(*commit));
	if (commit == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
		goto end;
	}

	if (!rid && (rc = fsl_stmt_get_id(q, 3, &rid))) {
		rc = RC(rc, "%s", "fsl_stmt_get_id");
		goto end;
	}
	/* Is there a more efficient way to get the parent? */
	commit->puuid = fsl_db_g_text(db, NULL,
	    "SELECT uuid FROM plink, blob WHERE plink.cid=%d "
	    "AND blob.rid=plink.pid AND plink.isprim", rid);
	commit->prid = fsl_uuid_to_rid(f, commit->puuid);
	commit->uuid = fsl_strdup(fsl_stmt_g_text(q, 0, NULL));
	commit->rid = rid;
	commit->type = fsl_strdup(type);
	commit->diff_type = diff_type;
	commit->timestamp = fsl_strdup(fsl_stmt_g_text(q, 1, NULL));
	commit->user = fsl_strdup(fsl_stmt_g_text(q, 2, NULL));
	commit->branch = fsl_strdup(fsl_stmt_g_text(q, 5, NULL));
	commit->comment = fsl_strdup(comment ? fsl_buffer_str(&buf) : "");
	fsl_buffer_clear(&buf);

	*ptr = commit;
end:
	return rc;
}

static int
signal_tl_thread(struct fnc_view *view, int wait)
{
	struct fnc_tl_thread_cx	*cx = &view->state.timeline.thread_cx;
	int			 rc = 0;

	while (cx->ncommits_needed > 0) {
		if (cx->timeline_end)
			break;

		/* Wake timeline thread. */
		if ((rc = pthread_cond_signal(&cx->commit_consumer)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_cond_signal");

		/*
		 * Mutex will be released while view_loop().view_input() waits
		 * in wgetch(), at which point the timeline thread will run.
		 */
		if (!wait)
			break;

		/* Show status update in timeline view. */
		show_timeline_view(view);
		update_panels();
		doupdate();

		/* Wait while the next commit is being loaded. */
		if ((rc = pthread_cond_wait(&cx->commit_producer, &fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_cond_wait");

		/* Show status update in timeline view. */
		show_timeline_view(view);
		update_panels();
		doupdate();
	}

	return cx->rc;
}

static int
draw_commits(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fnc_tl_thread_cx		*tcx = &s->thread_cx;
	struct commit_entry		*entry = s->selected_commit;
	struct fnc_colour		*c = NULL;
	const char			*search_str = NULL;
	char				*headln = NULL, *idxstr = NULL;
	char				*branch = NULL, *type = NULL;
	char				*uuid = NULL;
	wchar_t				*wcstr;
	int				 ncommits = 0, rc = 0, wstrlen = 0;
	int				 ncols_needed, max_usrlen = -1;

	if (s->selected_commit && !(view->searching != SEARCH_DONE &&
	    view->search_status == SEARCH_WAITING)) {
		uuid = fsl_strdup(s->selected_commit->commit->uuid);
		branch = fsl_strdup(s->selected_commit->commit->branch);
		type = fsl_strdup(s->selected_commit->commit->type);
	}

	if (s->thread_cx.ncommits_needed > 0) {
		if ((idxstr = fsl_mprintf(" [%d/%d] %s",
		    entry ? entry->idx + 1 : 0, s->commits.ncommits,
		    (view->searching && !view->search_status) ?
		    "searching..." : "loading...")) == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			goto end;
		}
	} else {
		if (view->searching) {
			if (view->search_status == SEARCH_COMPLETE)
				search_str = "no more matches";
			else if (view->search_status == SEARCH_NO_MATCH)
				search_str = "no matches found";
			else if (view->search_status == SEARCH_WAITING)
				search_str = "searching...";
		}

		if ((idxstr = fsl_mprintf("%s [%d/%d] %s",
		    !fsl_strcmp(uuid, s->curr_ckout_uuid) ? " [current]" : "",
		    entry ? entry->idx + 1 : 0, s->commits.ncommits,
		    search_str ? search_str : (branch ? branch : "")))
		    == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			goto end;
		}
	}
	/*
	 * Compute cols needed to fit all components of the headline to truncate
	 * the hash component if needed. wiki, tag, and ticket artifacts don't
	 * have a branch component, checkins and some technotes do, so add a col
	 * for the space separator. Same applies if search_str is being shown.
	 */
	ncols_needed = fsl_strlen(type) + fsl_strlen(idxstr) + FSL_STRLEN_K256
	    + (!search_str && (!fsl_strcmp(type, "wiki") ||
	    !fsl_strcmp(type, "tag")  || !fsl_strcmp(type, "ticket") ||
	    (!branch && !fsl_strcmp(type, "technote"))) ? 0 : 1);
	/* If a path has been requested, display it in the headline. */
	if (s->path[1]) {
		if ((headln = fsl_mprintf("%s%c%.*s %s%s", type ? type : "",
		    type ? ' ' : SPINNER[tcx->spin_idx], view->ncols <
		    ncols_needed ? view->ncols - (ncols_needed -
		    FSL_STRLEN_K256) : FSL_STRLEN_K256, uuid ? uuid :
		    "........................................",
		    s->path, idxstr)) == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			headln = NULL;
			goto end;
		}
	} else if ((headln = fsl_mprintf("%s%c%.*s%s", type ? type : "", type ?
	    ' ' : SPINNER[tcx->spin_idx], view->ncols < ncols_needed ?
	    view->ncols - (ncols_needed - FSL_STRLEN_K256) : FSL_STRLEN_K256,
	    uuid ? uuid : "........................................", idxstr))
	    == NULL) {
		rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		headln = NULL;
		goto end;
	}
	if (SPINNER[++tcx->spin_idx] == '\0')
		tcx->spin_idx = 0;
	rc = formatln(&wcstr, &wstrlen, headln, view->ncols, 0);
	if (rc)
		goto end;

	werase(view->window);

	if (screen_is_shared(view))
		wstandout(view->window);
	if (s->colour)
		c = get_colour(&s->colours, FNC_COMMIT_ID);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, wcstr);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	while (wstrlen < view->ncols) {
		waddch(view->window, ' ');
		++wstrlen;
	}
	if (screen_is_shared(view))
		wstandend(view->window);
	fsl_free(wcstr);
	if (view->nlines <= 1)
		goto end;

	/* Parse commits to be written on screen for the longest username. */
	entry = s->first_commit_onscreen;
	while (entry) {
		wchar_t		*usr_wcstr;
		char		*user;
		int		 usrlen;
		if (ncommits >= view->nlines - 1)
			break;
		user = fsl_strdup(entry->commit->user);
		if (user == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		if (strpbrk(user, "<@>") != NULL)
			parse_emailaddr_username(&user);
		rc = formatln(&usr_wcstr, &usrlen, user, view->ncols, 0);
		if (max_usrlen < usrlen)
			max_usrlen = usrlen;
		fsl_free(usr_wcstr);
		fsl_free(user);
		++ncommits;
		entry = TAILQ_NEXT(entry, entries);
	}

	ncommits = 0;
	entry = s->first_commit_onscreen;
	s->last_commit_onscreen = s->first_commit_onscreen;
	while (entry) {
		if (ncommits >= view->nlines - 1)
			break;
		if (ncommits == s->selected_idx)
			wattr_on(view->window, A_REVERSE, NULL);
		rc = write_commit_line(view, entry->commit, max_usrlen);
		if (ncommits == s->selected_idx)
			wattr_off(view->window, A_REVERSE, NULL);
		++ncommits;
		s->last_commit_onscreen = entry;
		entry = TAILQ_NEXT(entry, entries);
	}
	draw_vborder(view);

end:
	free(branch);
	free(type);
	free(uuid);
	free(idxstr);
	free(headln);
	return rc;
}

static void
parse_emailaddr_username(char **username)
{
	char	*lt, *usr;

	lt = strchr(*username, '<');
	if (lt && lt[1] != '\0') {
		usr = fsl_strdup(++lt);
		fsl_free(*username);
	} else
		usr = *username;
	usr[strcspn(usr, "@>")] = '\0';

	*username = usr;
}

static int
formatln(wchar_t **ptr, int *wstrlen, const char *mbstr, int column_limit,
    int start_column)
{
	wchar_t		*wline = NULL;
	size_t		 i, wlen;
	int		 rc = 0, cols = 0;

	*ptr = NULL;
	*wstrlen = 0;

	rc = multibyte_to_wchar(mbstr, &wline, &wlen);
	if (rc)
		return rc;

	if (wlen > 0 && wline[wlen - 1] == L'\n') {
		wline[wlen - 1] = L'\0';
		wlen--;
	}
	if (wlen > 0 && wline[wlen - 1] == L'\r') {
		wline[wlen - 1] = L'\0';
		wlen--;
	}

	i = 0;
	while (i < wlen) {
		int width = wcwidth(wline[i]);

		if (width == 0) {
			i++;
			continue;
		}

		if (width == 1 || width == 2) {
			if (cols + width > column_limit)
				break;
			cols += width;
			i++;
		} else if (width == -1) {
			if (wline[i] == L'\t') {
				width = TABSIZE -
				    ((cols + column_limit) % TABSIZE);
			} else {
				width = 1;
				wline[i] = L'.';
			}
			if (cols + width > column_limit)
				break;
			cols += width;
			i++;
		} else {
			rc = RC(FSL_RC_RANGE, "%s", "wcwidth");
			goto end;
		}
	}
	wline[i] = L'\0';
	if (wstrlen)
		*wstrlen = cols;
end:
	if (rc)
		free(wline);
	else
		*ptr = wline;
	return rc;
}

static int
multibyte_to_wchar(const char *src, wchar_t **dst, size_t *dstlen)
{
	int	rc = 0;

	/*
	 * mbstowcs POSIX extension specifies that the number of wchar that
	 * would be written are returned when first arg is a null pointer:
	 * https://en.cppreference.com/w/cpp/string/multibyte/mbstowcs
	 */
	*dstlen = mbstowcs(NULL, src, 0);
	if (*dstlen == (size_t)-1) {
		if (errno == EILSEQ)
			return RC(FSL_RC_RANGE,
			    "invalid multibyte character [%s]", src);
		return RC(FSL_RC_MISUSE, "mbstowcs(%s)", src);
	}


	*dst = NULL;
	*dst = fsl_malloc(sizeof(wchar_t) * (*dstlen + 1));
	if (*dst == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "malloc");
		goto end;
	}

	if (mbstowcs(*dst, src, *dstlen) != *dstlen)
		rc = RC(FSL_RC_SIZE_MISMATCH, "mbstowcs(%s)", src);

end:
	if (rc) {
		fsl_free(*dst);
		*dst = NULL;
		*dstlen = 0;
	}

	return rc;
}

/*
 * When the terminal is >= 110 columns wide, the commit summary line in the
 * timeline view will take the form:
 *
 *   DATE UUID USERNAME  COMMIT-COMMENT
 *
 * Assuming an 8-character username, this scheme provides 80 characters for the
 * comment, which should be sufficient considering it's suggested good practice
 * to limit commit comment summary lines to a maximum 50 characters, and most
 * plaintext-based conventions suggest not exceeding 72-80 characters.
 *
 * When < 110 columns, the (abbreviated 9-character) UUID will be elided.
 */
static int
write_commit_line(struct fnc_view *view, struct fnc_commit_artifact *commit,
    int max_usrlen)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fnc_colour		*c = NULL;
	wchar_t				*usr_wcstr = NULL, *wcomment = NULL;
	char				*comment0 = NULL, *comment = NULL;
	char				*date = NULL;
	char				*eol = NULL, *pad = NULL, *user = NULL;
	size_t				 i = 0;
	int				 col_pos, ncols_avail, usrlen;
	int				 commentlen, rc = 0;

	/* Trim time component from timestamp for the date field. */
	date = fsl_strdup(commit->timestamp);
	while (!fsl_isspace(date[i++])) {}
	date[i] = '\0';
	col_pos = MIN(view->ncols, ISO8601_DATE_ONLY + 1);
	if (s->colour)
		c = get_colour(&s->colours, FNC_DATE_STR);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddnstr(view->window, date, col_pos);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	if (col_pos > view->ncols)
		goto end;

	/* If enough columns, write abbreviated commit hash. */
	if (view->ncols >= 110) {
		if (s->colour)
			c = get_colour(&s->colours, FNC_COMMIT_ID);
		if (c)
			wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
		wprintw(view->window, "%.9s ", commit->uuid);
		if (c)
			wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
		col_pos += 10;
		if (col_pos > view->ncols)
			goto end;
	}

	/*
	 * Parse username from emailaddr if needed, and postfix username
	 * with as much whitespace as needed to fill two spaces beyond
	 * the longest username on the screen.
	 */
	user = fsl_strdup(commit->user);
	if (user == NULL)
		goto end;
	if (strpbrk(user, "<@>") != NULL)
		parse_emailaddr_username(&user);
	rc = formatln(&usr_wcstr, &usrlen, user, view->ncols - col_pos,
	    col_pos);
	if (rc)
		goto end;
	if (s->colour)
		c = get_colour(&s->colours, FNC_USER_STR);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, usr_wcstr);
	pad = fsl_mprintf("%*c",  max_usrlen - usrlen + 2, ' ');
	waddstr(view->window, pad);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	col_pos += (max_usrlen + 2);
	if (col_pos > view->ncols)
		goto end;

	/* Only show comment up to the first newline character. */
	comment0 = fsl_strdup(commit->comment);
	comment = comment0;
	if (comment == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	while (*comment == '\n')
		++comment;
	eol = strchr(comment, '\n');
	if (eol)
		*eol = '\0';
	ncols_avail = view->ncols - col_pos;
	rc = formatln(&wcomment, &commentlen, comment, ncols_avail, col_pos);
	if (rc)
		goto end;
	waddwstr(view->window, wcomment);
	col_pos += commentlen;
	while (col_pos < view->ncols) {
		waddch(view->window, ' ');
		++col_pos;
	}
end:
	fsl_free(date);
	fsl_free(user);
	fsl_free(usr_wcstr);
	fsl_free(pad);
	fsl_free(comment0);
	fsl_free(wcomment);
	return rc;
}

static int
view_input(struct fnc_view **new, int *done, struct fnc_view *view,
    struct view_tailhead *views)
{
	struct fnc_view	*v;
	int		 ch, rc = 0;

	*new = NULL;

	/* Clear search indicator string. */
	if (view->search_status == SEARCH_COMPLETE ||
	    view->search_status == SEARCH_NO_MATCH)
		view->search_status = SEARCH_CONTINUE;

	if (view->searching && view->search_status == SEARCH_WAITING) {
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		sched_yield();
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		rc = view->search_next(view);
		return rc;
	}

	nodelay(stdscr, FALSE);
	/* Allow thread to make progress while waiting for input. */
	if ((rc = pthread_mutex_unlock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");
	ch = wgetch(view->window);
	if ((rc = pthread_mutex_lock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	if (rec_sigwinch || rec_sigcont) {
		fnc_resizeterm();
		rec_sigwinch = 0;
		rec_sigcont = 0;
		TAILQ_FOREACH(v, views, entries) {
			if ((rc = view_resize(v)))
				return rc;
			if ((rc = v->input(new, v, KEY_RESIZE)))
				return rc;
			if (v->child) {
				if ((rc = view_resize(v->child)))
					return rc;
				rc = v->child->input(new, v->child, KEY_RESIZE);
				if (rc)
					return rc;
			}
		}
	}

	switch (ch) {
	case '\t':
		if (view->child) {
			view->active = false;
			view->child->active = true;
			view->focus_child = true;
		} else if (view->parent) {
			view->active = false;
			view->parent->active = true;
			view->parent->focus_child = false;
		}
		break;
	case KEY_F(1):
	case 'H':
	case '?':
		help(view);
		break;
	case 'q':
		rc = view->input(new, view, ch);
		view->egress = true;
		break;
	case 'f':
		if (view_is_parent(view)) {
			if (view->child == NULL)
				break;
			if (screen_is_split(view->child)) {
				view->active = false;
				view->child->active = true;
				rc = make_fullscreen(view->child);
			} else
				rc = make_splitscreen(view->child);
			if (rc)
				break;
			rc = view->child->input(new, view->child, KEY_RESIZE);
		} else {
			if (screen_is_split(view)) {
				view->parent->active = false;
				view->active = true;
				rc = make_fullscreen(view);
			} else
				rc = make_splitscreen(view);
			if (rc)
				break;
			rc = view->input(new, view, KEY_RESIZE);
		}
		break;
	case '/':
		if (view->search_init)
			view_search_start(view);
		else
			rc = view->input(new, view, ch);
		break;
	case 'N':
	case 'n':
		if (view->started_search && view->search_next) {
			view->searching = (ch == 'n' ?
			    SEARCH_FORWARD : SEARCH_REVERSE);
			view->search_status = SEARCH_WAITING;
			rc = view->search_next(view);
		} else
			rc = view->input(new, view, ch);
		break;
	case KEY_RESIZE:
		break;
	case ERR:
		break;
	case 'Q':
		*done = 1;
		break;
	default:
		rc = view->input(new, view, ch);
		break;
	}

	return rc;
}

static int
help(struct fnc_view *view)
{
	FILE			*help = NULL;
	char			*title = NULL;
	static const char	*keys[][2] = {
	    {""},
	    {""}, /* Global */
	    {"  H,?,F1           ", "  ❬H❭❬?❭❬F1❭      "},
	    {"  k,<Up>           ", "  ❬↑❭❬k❭          "},
	    {"  j,<Down>         ", "  ❬↓❭❬j❭          "},
	    {"  C-b,PgUp         ", "  ❬C-b❭❬PgUp❭     "},
	    {"  C-f,PgDn         ", "  ❬C-f❭❬PgDn❭     "},
	    {"  gg,Home          ", "  ❬gg❭❬Home❭      "},
	    {"  G,End            ", "  ❬G❭❬End❭        "},
	    {"  Tab              ", "  ❬TAB❭           "},
	    {"  c                ", "  ❬c❭             "},
	    {"  f                ", "  ❬f❭             "},
	    {"  /                ", "  ❬/❭             "},
	    {"  n                ", "  ❬n❭             "},
	    {"  N                ", "  ❬N❭             "},
	    {"  q                ", "  ❬q❭             "},
	    {"  Q                ", "  ❬Q❭             "},
	    {""},
	    {""}, /* Timeline */
	    {"  <,,              ", "  ❬<❭❬,❭          "},
	    {"  >,.              ", "  ❬>❭❬.❭          "},
	    {"  Enter,Space      ", "  ❬Enter❭❬Space❭  "},
	    {"  t                ", "  ❬t❭             "},
	    {""},
	    {""}, /* Diff */
	    {"  Space            ", "  ❬Space❭         "},
	    {"  i                ", "  ❬i❭             "},
	    {"  v                ", "  ❬v❭             "},
	    {"  w                ", "  ❬w❭             "},
	    {"  -,_              ", "  ❬-❭❬_❭          "},
	    {"  +,=              ", "  ❬+❭❬=❭          "},
	    {"  C-k,K,<,,        ", "  ❬C-k❭❬K❭❬<❭❬,❭  "},
	    {"  C-j,J,>,.        ", "  ❬C-j❭❬J❭❬>❭❬.❭  "},
	    {""},
	    {""}, /* Tree */
	    {"  l,Enter,<Right>  ", "  ❬→❭❬l❭❬Enter❭   "},
	    {"  h,<BS>,<Left>    ", "  ❬←❭❬h❭❬⌫❭       "},
	    {"  i                ", "  ❬i❭             "},
	    {"  t                ", "  ❬t❭             "},
	    {""},
	    {""}, /* Blame */
	    {"  Space            ", "  ❬Space❭         "},
	    {"  Enter            ", "  ❬Enter❭         "},
	    {"  b                ", "  ❬b❭             "},
	    {"  p                ", "  ❬p❭             "},
	    {"  B                ", "  ❬B❭             "},
	    {""},
	    {""}, /* Branch */
	    {"  Enter,Space      ", "  ❬Enter❭❬Space❭  "},
	    {"  d                ", "  ❬d❭             "},
	    {"  i                ", "  ❬i❭             "},
	    {"  t                ", "  ❬t❭             "},
	    {"  R,<C-l>          ", "  ❬R❭❬C-l❭        "},
	    {""},
	    {""},
	    {0}
	};
	static const char *desc[] = {
	    "",
	    "Global",
	    "Open in-app help",
	    "Move selection cursor or page up one line",
	    "Move selection cursor or page down one line",
	    "Scroll up one page",
	    "Scroll down one page",
	    "Jump to first line or start of the view",
	    "Jump to last line or end of the view",
	    "Switch focus between open views",
	    "Toggle coloured output",
            "Toggle fullscreen",
	    "Open prompt to enter search term (not available in this view)",
	    "Find next line or token matching the current search term",
	    "Find previous line or token matching the current search term",
            "Quit the active view",
	    "Quit the program",
	    "",
	    "Timeline",
	    "Move selection cursor up one commit",
	    "Move selection cursor down one commit",
	    "Open diff view of the selected commit",
	    "Display a tree reflecting the state of the selected commit",
	    "",
	    "Diff",
	    "Scroll down one page of diff output",
	    "Toggle inversion of diff output",
	    "Toggle verbosity of diff output",
	    "Toggle ignore whitespace-only changes in diff",
	    "Decrease the number of context lines",
	    "Increase the number of context lines",
	    "Display diff of next (newer) commit in the timeline",
	    "Display diff of previous (older) commit in the timeline",
	    "",
	    "Tree",
	    "Move into the selected directory",
	    "Return to the parent directory",
	    "Toggle display of file artifact SHA hashes",
	    "Display timeline of all commits modifying the selected entry",
	    "",
	    "Blame",
	    "Scroll down one page",
	    "Display the diff of the commit corresponding to the selected line",
	    "Blame the version of the file found in the selected line's commit",
	    "Blame the version of the file found in the selected line's parent "
	    "commit",
	    "Reload the previous blamed version of the file",
	    "",
	    "Branch",
	    "Display the timeline of the currently selected branch",
	    "Toggle display of the date when the branch last received changes",
	    "Toggle display of the SHA hash that identifies the branch",
	    "Open a tree view of the currently selected branch",
	    "Reload view with all repostory branches and no filters applied",
	    "",
	    "  See fnc(1) for complete list of options and key bindings."
	};
	int	cs, ln, width = 0, rc = 0;

	cs = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) ? 1 : 0;

	title = fsl_mprintf("%s %s Help\n", fcli_progname(), PRINT_VERSION);
	if (title == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");

	help = tmpfile();
	if (help == NULL)
		return RC(FSL_RC_IO, "%s", "tmpfile");

	/*
	 * Format help text, and compute longest line and total number of
	 * lines in text to be displayed to determine pad dimensions.
	 */
	width = fsl_strlen(title);
	for (ln = 0; keys[ln][0]; ++ln) {
		if (keys[ln][1]) {
			width = MAX((fsl_size_t)width,
			    fsl_strlen(keys[ln][cs]) + fsl_strlen(desc[ln]));
		}
		fsl_fprintf(help, "%s%s%c", keys[ln][cs], desc[ln],
		    keys[ln + 1] ? '\n' : 0);
	}
	rewind(help);

	rc = padpopup(view, width, ln, help, title);
	if (fclose(help) == EOF)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");

	fsl_free(title);
	return rc;
}

/*
 * Create popup pad in which to write the supplied txt string and optional
 * title. The pad is contained within a window that is offset four columns in
 * and two lines down from the parent window.
 */
static int
padpopup(struct fnc_view *view, int width, int height, FILE *txt,
    const char *title)
{
	WINDOW		*win, *content;
	char		*line = NULL;
	ssize_t		 linelen;
	size_t		 linesz;
	int		 ch, cury, end, wy, wx, x0, y0;

	x0 = 4;		/* Number of columns to border window. */
	y0 = 2;		/* Number of lines to border window. */
	cury = 0;
	wx = getmaxx(view->window) - ((x0 + 1) * 2); /* Width of window. */
	wy = getmaxy(view->window) - ((y0 + 1) * 2); /* Height of window */
	ch = ERR;

	if ((win = newwin(wy, wx, y0, x0)) == 0)
		return RC(FSL_RC_ERROR, "%s", "newwin");
	if ((content = newpad(height + 1, width + 1)) == 0) {
		delwin(win);
		return RC(FSL_RC_ERROR, "%s", "newpad");
	}

	doupdate();
	keypad(content, TRUE);

	/* Write text content to pad. */
	if (title)
		centerprint(content, 0, 0, width, title, 0);
	while ((linelen = getline(&line, &linesz, txt)) != -1)
		waddstr(content, line);
	fsl_free(line);

	end = (getcury(content) - (wy - 3));  /* No. lines past end of pad. */
	do {
		switch (ch) {
			case KEY_UP:
			case 'k':
				if (cury > 0)
					--cury;
				break;
			case KEY_DOWN:
			case 'j':
				if (cury < end)
					++cury;
				break;
			case KEY_PPAGE:
			case CTRL('b'):
				if (cury > 0) {
					cury -= wy / 2;
					if (cury < 0)
						cury = 0;
				}
				break;
			case KEY_NPAGE:
			case CTRL('f'):
			case ' ':
				if (cury < end) {
					cury += wy / 2;
					if (cury > end)
						cury = end;
				}
				break;
			case 'g':
				if (!fnc_home(view))
					break;
				/* FALL THROUGH */
			case KEY_HOME:
				cury = 0;
				break;
			case KEY_END:
			case 'G':
				cury = end;
				break;
			case ERR:
			default:
				break;
		}
		werase(win);
		box(win, 0, 0);
		wnoutrefresh(win);
		pnoutrefresh(content, cury, 0, y0 + 1, x0 + 1, wy, wx);
		doupdate();
	} while ((ch = wgetch(content)) != 'q' && ch != KEY_ESCAPE
	    && ch != ERR);

	/* Destroy window. */
	werase(win);
	wrefresh(win);
	delwin(win);
	delwin(content);

	/* Restore fnc window content. */
	touchwin(view->window);
	wnoutrefresh(view->window);
	doupdate();

	return 0;
}

static void
centerprint(WINDOW *win, int starty, int startx, int cols, const char *str,
    chtype colour)
{
	int	x, y;

	if (win == NULL)
		win = stdscr;

	getyx(win, y, x);
	x = startx ? startx : x;
	y = starty ? starty : y;
	if (!cols)
		cols = getmaxx(win);

	x = startx + (cols - fsl_strlen(str)) / 2;
	wattron(win, colour ? colour : A_UNDERLINE);
	mvwprintw(win, y, x, "%s", str);
	wattroff(win, colour ? colour : A_UNDERLINE);
	refresh();
}

static int
tl_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fnc_view			*diff_view = NULL, *tree_view = NULL;
	int				 rc = 0, start_col = 0;

	switch (ch) {
	case KEY_DOWN:
	case 'j':
	case '.':
	case '>':
		if (s->first_commit_onscreen == NULL)
			break;
		if (s->selected_idx < MIN(view->nlines - 2,
		    s->commits.ncommits - 1))
			++s->selected_idx;
		else if ((rc = timeline_scroll_down(view, 1)))
			break;
		select_commit(s);
		break;
	case KEY_NPAGE:
	case CTRL('f'): {
		struct commit_entry *first;
		if ((first = s->first_commit_onscreen) == NULL)
			break;
		if ((rc = timeline_scroll_down(view, view->nlines - 1)))
			break;
		if (first == s->first_commit_onscreen && s->selected_idx <
		    MIN(view->nlines - 2, s->commits.ncommits - 1))
			/* At bottom of timeline. */
			s->selected_idx = MIN(view->nlines - 2,
			    s->commits.ncommits - 1);
		select_commit(s);
		break;
	}
	case KEY_END:
	case 'G':
		view->search_status = SEARCH_FOR_END;
		view_search_start(view);
		break;
	case 'k':
	case KEY_UP:
	case '<':
	case ',':
		if (s->first_commit_onscreen == NULL)
			break;
		if (s->selected_idx > 0)
			--s->selected_idx;
		else
			timeline_scroll_up(s, 1);
		select_commit(s);
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->first_commit_onscreen == NULL)
			break;
		if (TAILQ_FIRST(&s->commits.head) == s->first_commit_onscreen)
			s->selected_idx = 0;
		else
			timeline_scroll_up(s, view->nlines - 1);
		select_commit(s);
		break;
	case 'g':
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	case KEY_HOME:
		if (s->first_commit_onscreen == NULL)
			break;
		s->selected_idx = 0;
		timeline_scroll_up(s, s->commits.ncommits);
		select_commit(s);
		break;
	case KEY_RESIZE:
		if (s->selected_idx > view->nlines - 2)
			s->selected_idx = view->nlines - 2;
		if (s->selected_idx > s->commits.ncommits - 1)
			s->selected_idx = s->commits.ncommits - 1;
		select_commit(s);
		if (s->commits.ncommits < view->nlines - 1 &&
		    !s->thread_cx.timeline_end) {
			s->thread_cx.ncommits_needed += (view->nlines - 1) -
			    s->commits.ncommits;
			rc = signal_tl_thread(view, 1);
		}
		break;
	case KEY_ENTER:
	case ' ':
	case '\r':
		if (s->selected_commit == NULL)
			break;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		if ((rc = init_diff_commit(&diff_view, start_col,
		    s->selected_commit->commit, view)))
			break;
		view->active = false;
		diff_view->active = true;
		if (view_is_parent(view)) {
			if (view->child != NULL) {
				rc = view_close(view->child);
				view->child = NULL;
			}
			if (rc)
				return rc;
			view->child = diff_view;
			diff_view->parent = view;
			view->focus_child = true;
		} else
			*new_view = diff_view;
		break;
	case 'c':
		s->colour = !s->colour;
		break;
	case 't':
		if (s->selected_commit == NULL)
			break;
		if (!fsl_rid_is_a_checkin(fcli_cx(),
		    s->selected_commit->commit->rid)) {
			wattr_on(view->window, A_BOLD, NULL);
			mvwaddstr(view->window,
			    view->start_ln + view->nlines - 1, 0,
			    "-- tree requires check-in artifact --");
			wclrtoeol(view->window);
			wattr_off(view->window, A_BOLD, NULL);
			fcli_err_reset();
			rc = 0;
			update_panels();
			doupdate();
			sleep(1);
			break;
		}
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		rc = browse_commit_tree(&tree_view, start_col,
		    s->selected_commit, s->path);
		if (rc)
			break;
		s->thread_cx.tree_open = true;
		view->active = false;
		tree_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				return rc;
			view_set_child(view, tree_view);
			view->focus_child = true;
		} else
			*new_view = tree_view;
		break;
	case 'q':
		s->quit = 1;
		break;
	default:
		break;
	}

	return rc;
}

static int
timeline_scroll_down(struct fnc_view *view, int maxscroll)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct commit_entry		*pentry;
	int				 rc = 0, nscrolled = 0, ncommits_needed;

	if (s->last_commit_onscreen == NULL)
		return 0;

	ncommits_needed = s->last_commit_onscreen->idx + 1 + maxscroll;
	if (s->commits.ncommits < ncommits_needed &&
	    !s->thread_cx.timeline_end) {
		/* Signal timeline thread for n commits needed. */
		s->thread_cx.ncommits_needed += maxscroll;
		rc = signal_tl_thread(view, 1);
		if (rc)
			return rc;
	}

	do {
		pentry = TAILQ_NEXT(s->last_commit_onscreen, entries);
		if (pentry == NULL)
			break;

		s->last_commit_onscreen = pentry;

		pentry = TAILQ_NEXT(s->first_commit_onscreen, entries);
		if (pentry == NULL)
			break;
		s->first_commit_onscreen = pentry;
	} while (++nscrolled < maxscroll);

	return rc;
}

static void
timeline_scroll_up(struct fnc_tl_view_state *s, int maxscroll)
{
	struct commit_entry	*entry;
	int			 nscrolled = 0;

	entry = TAILQ_FIRST(&s->commits.head);
	if (s->first_commit_onscreen == entry)
		return;

	entry = s->first_commit_onscreen;
	while (entry && nscrolled < maxscroll) {
		entry = TAILQ_PREV(entry, commit_tailhead, entries);
		if (entry) {
			s->first_commit_onscreen = entry;
			++nscrolled;
		}
	}
}

static void
select_commit(struct fnc_tl_view_state *s)
{
	struct commit_entry	*entry;
	int			 ncommits = 0;

	entry = s->first_commit_onscreen;
	while (entry) {
		if (ncommits == s->selected_idx) {
			s->selected_commit = entry;
			break;
		}
		entry = TAILQ_NEXT(entry, entries);
		++ncommits;
	}
}

static int
make_splitscreen(struct fnc_view *view)
{
	int	 rc = 0;

	view->start_ln = 0;
	view->start_col = view_split_start_col(0);
	view->nlines = LINES;
	view->ncols = COLS - view->start_col;
	view->lines = LINES;
	view->cols = COLS;
	if ((rc = view_resize(view)))
		return rc;

	if (mvwin(view->window, view->start_ln, view->start_col) == ERR)
		return RC(FSL_RC_ERROR, "%s", "mvwin");

	return rc;
}

static int
make_fullscreen(struct fnc_view *view)
{
	int	 rc = 0;

	view->start_col = 0;
	view->start_ln = 0;
	view->nlines = LINES;
	view->ncols = COLS;
	view->lines = LINES;
	view->cols = COLS;
	if ((rc = view_resize(view)))
		return rc;

	if (mvwin(view->window, view->start_ln, view->start_col) == ERR)
		return RC(FSL_RC_ERROR, "%s", "mvwin");

	return rc;
}

/*
 * Only open a new view in a splitscreen if the console is >= 120 columns wide.
 * Otherwise, open in the current view. If splitting the screen, make the new
 * panel the largest of 80 columns or half the current column width.
 */
static int
view_split_start_col(int start_col)
{
	if (start_col > 0 || COLS < 120)
		return 0;
	return (COLS - MAX(COLS / 2, 80));
}

static int
view_search_start(struct fnc_view *view)
{
	char	pattern[BUFSIZ];
	int	retval;
	int	rc = 0;

	if (view->started_search) {
		regfree(&view->regex);
		view->searching = SEARCH_DONE;
		memset(&view->regmatch, 0, sizeof(view->regmatch));
	}
	view->started_search = false;

	if (view->nlines < 1)
		return rc;

	if (view->search_status == SEARCH_FOR_END) {
		view->search_init(view);
		view->started_search = true;
		view->searching = SEARCH_FORWARD;
		view->search_status = SEARCH_WAITING;
		view->state.timeline.thread_cx.endjmp = true;
		rc = view->search_next(view);

		return rc;
	}

	mvwaddstr(view->window, view->start_ln + view->nlines - 1, 0, "/");
	wclrtoeol(view->window);

	nocbreak();
	echo();
	retval = wgetnstr(view->window, pattern, sizeof(pattern));
	cbreak();
	noecho();
	if (retval == ERR)
		return rc;

	if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
		if ((rc = view->search_init(view))) {
			regfree(&view->regex);
			return rc;
		}
		view->started_search = true;
		view->searching = SEARCH_FORWARD;
		view->search_status = SEARCH_WAITING;
		rc = view->search_next(view);
	}

	return rc;
}

static int
tl_search_init(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;

	s->matched_commit = NULL;
	s->search_commit = NULL;
	return 0;
}

static int
tl_search_next(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct commit_entry		*entry;
	int				 rc = 0;

	if (!s->thread_cx.ncommits_needed && view->started_search)
		halfdelay(1);

	/* Show status update in timeline view. */
	show_timeline_view(view);
	update_panels();
	doupdate();

	if (s->search_commit) {
		int	ch;
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		ch = wgetch(view->window);
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		if (ch == KEY_BACKSPACE) {
			view->search_status = SEARCH_CONTINUE;
			return rc;
		}
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_NEXT(s->search_commit, entries);
		else
			entry = TAILQ_PREV(s->search_commit, commit_tailhead,
			    entries);
	} else if (s->matched_commit) {
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_NEXT(s->matched_commit, entries);
		else
			entry = TAILQ_PREV(s->matched_commit, commit_tailhead,
			    entries);
	} else {
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_FIRST(&s->commits.head);
		else
			entry = TAILQ_LAST(&s->commits.head, commit_tailhead);
	}

	while (1) {
		if (entry == NULL) {
			if (s->thread_cx.timeline_end && s->thread_cx.endjmp) {
				s->matched_commit = TAILQ_LAST(&s->commits.head,
				    commit_tailhead);
				view->search_status = SEARCH_COMPLETE;
				s->thread_cx.endjmp = false;
				break;
			}
			if (s->thread_cx.timeline_end || view->searching ==
			    SEARCH_REVERSE) {
				view->search_status = (s->matched_commit ==
				    NULL ?  SEARCH_NO_MATCH : SEARCH_COMPLETE);
				s->search_commit = NULL;
				cbreak();
				return rc;
			}
			/*
			 * Wake the timeline thread to produce more commits.
			 * Search will resume at s->search_commit upon return.
			 */
			++s->thread_cx.ncommits_needed;
			return signal_tl_thread(view, 0);
		}

		if (!s->thread_cx.endjmp && find_commit_match(entry->commit,
		    &view->regex)) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_commit = entry;
			break;
		}

		s->search_commit = entry;
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_NEXT(entry, entries);
		else
			entry = TAILQ_PREV(entry, commit_tailhead, entries);
	}

	if (s->matched_commit) {
		int cur = s->selected_commit->idx;
		while (cur < s->matched_commit->idx) {
			if ((rc = tl_input_handler(NULL, view, KEY_DOWN)))
				return rc;
			++cur;
		}
		while (cur > s->matched_commit->idx) {
			if ((rc = tl_input_handler(NULL, view, KEY_UP)))
				return rc;
			--cur;
		}
	}

	s->search_commit = NULL;
	cbreak();

	return rc;
}

static bool
find_commit_match(struct fnc_commit_artifact *commit,
regex_t *regex)
{
	regmatch_t	regmatch;

	if (regexec(regex, commit->user, 1, &regmatch, 0) == 0 ||
	    regexec(regex, (char *)commit->uuid, 1, &regmatch, 0) == 0 ||
	    regexec(regex, commit->comment, 1, &regmatch, 0) == 0 ||
	    (commit->branch && regexec(regex, commit->branch, 1, &regmatch, 0)
	     == 0))
		return true;

	return false;
}

static int
view_close(struct fnc_view *view)
{
        int	rc = 0;

	if (view->child) {
		view_close(view->child);
		view->child = NULL;
	}
	if (view->close)
		rc = view->close(view);
	if (view->panel)
		del_panel(view->panel);
	if (view->window)
		delwin(view->window);
	free(view);

	return rc;
}

static int
close_timeline_view(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fsl_list_state		 st = { FNC_COLOUR_OBJ };
	int				 rc = 0;

	rc = join_tl_thread(s);
	fsl_stmt_finalize(s->thread_cx.q);
	fnc_free_commits(&s->commits);
	fsl_list_clear(&s->colours, fsl_list_object_free, &st);
	regfree(&view->regex);
	fsl_free(s->path);
	s->path = NULL;

	return rc;
}

/* static void */
/* sspinner(void) */
/* { */
/* 	int idx; */

/* 	while (1) { */
/* 		for (idx = 0; idx < 4; ++idx) { */
/* 			printf("\b%c", "|/-\\"[idx]); */
/* 			fflush(stdout); */
/* 			ssleep(SPIN_INTERVAL); */
/* 		} */
/* 	} */
/* } */

static int
join_tl_thread(struct fnc_tl_view_state *s)
{
	void	*err;
	int	 rc = 0;

	if (s->thread_id) {
		s->quit = 1;

		if ((rc = pthread_cond_signal(&s->thread_cx.commit_consumer)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_cond_signal");
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		if ((rc = pthread_join(s->thread_id, &err)) ||
		    err == PTHREAD_CANCELED)
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_join");
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");

		s->thread_id = 0;
	}

	if ((rc = pthread_cond_destroy(&s->thread_cx.commit_consumer)))
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_destroy");

	if ((rc = pthread_cond_destroy(&s->thread_cx.commit_producer)))
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_destroy");

	return rc;
}

static void
fnc_free_commits(struct commit_queue *commits)
{
	while (!TAILQ_EMPTY(&commits->head)) {
		struct commit_entry	*entry;

		entry = TAILQ_FIRST(&commits->head);
		TAILQ_REMOVE(&commits->head, entry, entries);
		fnc_commit_artifact_close(entry->commit);
		free(entry);
		--commits->ncommits;
	}
}

static void
fnc_commit_artifact_close(struct fnc_commit_artifact *commit)
{
	struct fsl_list_state	st = { FNC_ARTIFACT_OBJ };

	if (commit->branch)
		fsl_free(commit->branch);
	if (commit->comment)
		fsl_free(commit->comment);
	if (commit->timestamp)
		fsl_free(commit->timestamp);
	if (commit->type)
		fsl_free(commit->type);
	if (commit->user)
		fsl_free(commit->user);
	fsl_free(commit->uuid);
	fsl_free(commit->puuid);
	fsl_list_clear(&commit->changeset, fsl_list_object_free, &st);
	fsl_list_reserve(&commit->changeset, 0);
	fsl_free(commit);
}

static int
fsl_list_object_free(void *elem, void *state)
{
	struct fsl_list_state *st = state;

	switch (st->obj) {
	case FNC_ARTIFACT_OBJ: {
		struct fsl_file_artifact *ffa = elem;
		fsl_free(ffa->fc->name);
		fsl_free(ffa->fc->uuid);
		fsl_free(ffa->fc->priorName);
		fsl_free(ffa->fc);
		fsl_free(ffa);
		break;
	}
	case FNC_COLOUR_OBJ: {
		struct fnc_colour *c = elem;
		regfree(&c->regex);
		fsl_free(c);
		break;
	}
	default:
		return RC(FSL_RC_MISSING_INFO,
		    "fsl_list_state.obj missing or invalid: %d", st->obj);
	}

	return 0;
}

static int
init_diff_commit(struct fnc_view **new_view, int start_col,
    struct fnc_commit_artifact *commit, struct fnc_view *timeline_view)
{
	struct fnc_view			*diff_view;
	int				 rc = 0;

	diff_view = view_open(0, 0, 0, start_col, FNC_VIEW_DIFF);
	if (diff_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_diff_view(diff_view, commit, DIFF_DEF_CTXT, fnc_init.ws,
	    fnc_init.invert, !fnc_init.quiet, timeline_view, true, NULL);
	if (!rc)
		*new_view = diff_view;

	return rc;
}

static int
open_diff_view(struct fnc_view *view, struct fnc_commit_artifact *commit,
    int context, bool ignore_ws, bool invert, bool verbosity,
    struct fnc_view *timeline_view, bool showmeta,
    struct fnc_pathlist_head *paths)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	int				 rc = 0;

	s->paths = paths;
	s->selected_commit = commit;
	s->first_line_onscreen = 1;
	s->last_line_onscreen = view->nlines;
	s->current_line = 1;
	s->f = NULL;
	s->context = context;
	s->sbs = 0;
	verbosity ? s->diff_flags |= FSL_DIFF_VERBOSE : 0;
	ignore_ws ? s->diff_flags |= FSL_DIFF_IGNORE_ALLWS : 0;
	invert ? s->diff_flags |= FSL_DIFF_INVERT : 0;
	s->timeline_view = timeline_view;
	s->colours = fsl_list_empty;
	s->colour = !fnc_init.nocolour && has_colors();
	s->showmeta = showmeta;

	if (s->colour)
		set_colours(&s->colours, FNC_VIEW_DIFF);
	if (timeline_view && screen_is_split(view))
		show_timeline_view(timeline_view); /* draw vborder */
	show_diff_status(view);

	s->line_offsets = NULL;
	s->nlines = 0;
	s->ncols = view->ncols;
	rc = create_diff(s);
	if (rc) {
		if (s->colour) {
			struct fsl_list_state st = { FNC_COLOUR_OBJ };
			fsl_list_clear(&s->colours, fsl_list_object_free, &st);
		}
		return rc;
	}

	view->show = show_diff;
	view->input = diff_input_handler;
	view->close = close_diff_view;
	view->search_init = diff_search_init;
	view->search_next = diff_search_next;

	return rc;
}

static void
show_diff_status(struct fnc_view *view)
{
	mvwaddstr(view->window, 0, 0, "generating diff...");
#ifdef __linux__
	wnoutrefresh(view->window);
#else
	update_panels();
#endif
	doupdate();
}

static int
create_diff(struct fnc_diff_view_state *s)
{
	FILE	*fout = NULL;
	char	*line, *st0 = NULL, *st = NULL;
	off_t	 lnoff = 0;
	int	 n, rc = 0;

	free(s->line_offsets);
	s->line_offsets = fsl_malloc(sizeof(off_t));
	if (s->line_offsets == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	s->nlines = 0;

	fout = tmpfile();
	if (fout == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "tmpfile");
		goto end;
	}
	if (s->f && fclose(s->f) == EOF) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");
		goto end;
	}
	s->f = fout;

	/*
	 * We'll diff artifacts of type "ci" (i.e., "checkin") separately, as
	 * it's a different process to diff the others (wiki, technote, etc.).
	 */
	if (s->selected_commit->diff_type == FNC_DIFF_COMMIT)
		rc = create_changeset(s->selected_commit);
	else if (s->selected_commit->diff_type == FNC_DIFF_BLOB)
		rc = diff_file_artifact(&s->buf, s->selected_commit->prid, NULL,
		    s->selected_commit->rid, NULL, FSL_CKOUT_CHANGE_MOD,
		    s->diff_flags, s->context, s->sbs,
		    s->selected_commit->diff_type);
	else if (s->selected_commit->diff_type == FNC_DIFF_WIKI)
		rc = diff_non_checkin(&s->buf, s->selected_commit,
		    s->diff_flags, s->context, s->sbs);
	if (rc)
		goto end;

	/*
	 * Delay assigning diff headline labels (i.e., diff id1 id2) till now
	 * because wiki parent commits are obtained in diff_non_checkin().
	 */
	if (s->selected_commit->puuid) {
		s->id1 = fsl_strdup(s->selected_commit->puuid);
		if (s->id1 == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else
		s->id1 = NULL;	/* Initial commit, tag, technote, etc. */
	if (s->selected_commit->uuid) {
		s->id2 = fsl_strdup(s->selected_commit->uuid);
		if (s->id2 == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else
		s->id2 = NULL;	/* Local work tree. */

	rc = add_line_offset(&s->line_offsets, &s->nlines, 0);
	if (rc)
		goto end;

	if (s->showmeta)
		write_commit_meta(s);

	/*
	 * Diff local changes on disk in the current checkout differently to
	 * checked-in versions: the former compares on disk file content with
	 * file artifacts; the latter compares file artifact blobs only.
	 */
	if (s->selected_commit->diff_type == FNC_DIFF_COMMIT)
		diff_commit(&s->buf, s->selected_commit, s->diff_flags,
		    s->context, s->sbs, s->paths);
	else if (s->selected_commit->diff_type == FNC_DIFF_CKOUT)
		diff_checkout(&s->buf, s->selected_commit->prid, s->diff_flags,
		    s->context, s->sbs, s->paths);

	/*
	 * Parse the diff buffer line-by-line to record byte offsets of each
	 * line for scrolling and searching in diff view.
	 */
	st0 = fsl_strdup(fsl_buffer_str(&s->buf));
	st = st0;
	lnoff = (s->line_offsets)[s->nlines - 1];
	while ((line = fnc_strsep(&st, "\n")) != NULL) {
		n = fprintf(s->f, "%s\n", line);
		lnoff += n;
		rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff);
		if (rc)
			goto end;
	}

	fputc('\n', s->f);
	++lnoff;
	rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff);
	if (rc)
		goto end;

end:
	free(st0);
	fsl_buffer_clear(&s->buf);
	if (s->f && fflush(s->f) != 0 && rc == 0)
		rc = RC(FSL_RC_IO, "%s", "fflush");
	return rc;
}

static int
create_changeset(struct fnc_commit_artifact *commit)
{
	fsl_cx		*f = fcli_cx();
	fsl_stmt	*st = NULL;
	fsl_list	 changeset = fsl_list_empty;
	int		 rc = 0;

	st = fsl_stmt_malloc();
	rc = fsl_cx_prepare(f, st,
	    "SELECT name, mperm, "
	    "(SELECT uuid FROM blob WHERE rid=mlink.pid), "
	    "(SELECT uuid FROM blob WHERE rid=mlink.fid), "
	    "(SELECT name FROM filename WHERE filename.fnid=mlink.pfnid) "
	    "FROM mlink JOIN filename ON filename.fnid=mlink.fnid "
	    "WHERE mlink.mid=%d AND NOT mlink.isaux "
	    "AND (mlink.fid > 0 "
	    "OR mlink.fnid NOT IN (SELECT pfnid FROM mlink WHERE mid=%d)) "
	    "ORDER BY name", commit->rid, commit->rid);
	if (rc)
		return RC(FSL_RC_DB, "%s", "fsl_cx_prepare");

	while ((rc = fsl_stmt_step(st)) == FSL_RC_STEP_ROW) {
		struct fsl_file_artifact *fdiff = NULL;
		const char *path, *oldpath, *olduuid, *uuid;
		/* TODO: Parse file mode to display in commit changeset. */
		/* int perm; */

		path = fsl_stmt_g_text(st, 0, NULL);	/* Current filename. */
		//perm = fsl_stmt_g_int32(st, 1);	/* File permissions. */
		olduuid = fsl_stmt_g_text(st, 2, NULL);	/* UUID before change */
		uuid = fsl_stmt_g_text(st, 3, NULL);	/* UUID after change. */
		oldpath = fsl_stmt_g_text(st, 4, NULL);	/* Old name, if chngd */

		fdiff = fsl_malloc(sizeof(struct fsl_file_artifact));
		fdiff->fc = fsl_malloc(sizeof(fsl_card_F));
		*fdiff->fc = fsl_card_F_empty;
		fdiff->fc->name = fsl_strdup(path);
		if (!uuid) {
			fdiff->fc->uuid = fsl_strdup(olduuid);
			fdiff->change = FSL_CKOUT_CHANGE_REMOVED;
		} else if (!olduuid) {
			fdiff->fc->uuid = fsl_strdup(uuid);
			fdiff->change = FSL_CKOUT_CHANGE_ADDED;
		} else if (oldpath) {
			fdiff->fc->uuid = fsl_strdup(uuid);
			fdiff->fc->priorName = fsl_strdup(oldpath);
			fdiff->change = FSL_CKOUT_CHANGE_RENAMED;
		} else {
			fdiff->fc->uuid = fsl_strdup(uuid);
			fdiff->change = FSL_CKOUT_CHANGE_MOD;
		}
		fsl_list_append(&changeset, fdiff);
	}

	commit->changeset = changeset;
	fsl_stmt_finalize(st);

	if (rc == FSL_RC_STEP_DONE)
		rc = 0;

	return rc;
}

static int
write_commit_meta(struct fnc_diff_view_state *s)
{
	char		*line = NULL, *st0 = NULL, *st = NULL;
	fsl_size_t	 linelen, idx = 0;
	off_t		 lnoff = 0;
	int		 n, rc = 0;

	if ((n = fprintf(s->f,"%s %s\n", s->selected_commit->type,
	    s->selected_commit->uuid)) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	if ((n = fprintf(s->f,"user: %s\n", s->selected_commit->user)) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	if ((n = fprintf(s->f,"tags: %s\n", s->selected_commit->branch ?
	    s->selected_commit->branch : "/dev/null")) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	if ((n = fprintf(s->f,"date: %s\n",
	    s->selected_commit->timestamp)) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	fputc('\n', s->f);
	++lnoff;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	st0 = fsl_strdup(s->selected_commit->comment);
	st = st0;
	if (st == NULL) {
		RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}
	while ((line = fnc_strsep(&st, "\n")) != NULL) {
		linelen = fsl_strlen(line);
		if (linelen >= s->ncols) {
			rc = wrapline(line, s->ncols, s, &lnoff);
			if (rc)
				goto end;
		}
		else {
			if ((n = fprintf(s->f, "%s\n", line)) < 0)
				goto end;
			lnoff += n;
			if ((rc = add_line_offset(&s->line_offsets, &s->nlines,
			    lnoff)))
				goto end;

		}
	}

	fputc('\n', s->f);
	++lnoff;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	for (idx = 0; idx < s->selected_commit->changeset.used; ++idx) {
		char				*changeline;
		struct fsl_file_artifact	*file_change;

		file_change = s->selected_commit->changeset.list[idx];

		switch (file_change->change) {
		case FSL_CKOUT_CHANGE_MOD:
			changeline = "[~] ";
			break;
		case FSL_CKOUT_CHANGE_ADDED:
			changeline = "[+] ";
			break;
		case FSL_CKOUT_CHANGE_RENAMED:
			changeline = fsl_mprintf("[>] %s -> ",
			   file_change->fc->priorName);
			break;
		case FSL_CKOUT_CHANGE_REMOVED:
			changeline = "[-] ";
			break;
		default:
			changeline = "[!] ";
			break;
		}
		if ((n = fprintf(s->f, "%s%s\n", changeline,
		    file_change->fc->name)) < 0)
			goto end;
		lnoff += n;
		if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
			goto end;
	}

end:
	free(st0);
	free(line);
	if (rc) {
		free(*&s->line_offsets);
		s->line_offsets = NULL;
		s->nlines = 0;
	}
	return rc;
}

/*
 * Wrap long lines at the terminal's available column width. The caller
 * must ensure the ncols_avail parameter has taken into account whether the
 * screen is currently split, and not mistakenly pass in the curses COLS macro
 * without deducting the parent panel's width. This function doesn't break
 * words, and will wrap at the end of the last word that can wholly fit within
 * the ncols_avail limit.
 */
static int
wrapline(char *line, fsl_size_t ncols_avail, struct fnc_diff_view_state *s,
    off_t *lnoff)
{
	char		*word;
	fsl_size_t	 wordlen, cursor = 0;
	int		 n = 0, rc = 0;

	while ((word = fnc_strsep(&line, " ")) != NULL) {
		wordlen = fsl_strlen(word);
		if ((cursor + wordlen) >= ncols_avail) {
			fputc('\n', s->f);
			++(*lnoff);
			rc = add_line_offset(&s->line_offsets, &s->nlines,
			    *lnoff);
			if (rc)
				return rc;
			cursor = 0;
		}
		if ((n  = fprintf(s->f, "%s ", word)) < 0)
			return rc;
		*lnoff += n;
		cursor += n;
	}
	fputc('\n', s->f);
	++(*lnoff);
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, *lnoff)))
		return rc;

	return 0;
}

static int
add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
{
	off_t	*p;

	p = fsl_realloc(*line_offsets, (*nlines + 1) * sizeof(off_t));
	if (p == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_realloc");
	*line_offsets = p;
	(*line_offsets)[*nlines] = off;
	(*nlines)++;

	return 0;
}

/*
 * Fill the buffer with the differences between commit->uuid and commit->puuid.
 * commit->rid (to load into deck d2) is the *this* version, and commit->puuid
 * (to be loaded into deck d1) is the version we diff against. Step through the
 * deck of F(ile) cards from both versions to determine: (1) if we have new
 * files added (i.e., no F card counterpart in d1); (2) files deleted (i.e., no
 * F card counterpart in d2); (3) or otherwise the same file (i.e., F card
 * exists in both d1 and d2). In cases (1) and (2), we call diff_file_artifact()
 * to dump the complete content of the added/deleted file if FSL_DIFF_VERBOSE is
 * set, otherwise only diff metatadata will be output. In case (3), if the
 * hash (UUID) of each F card is the same, there are no changes; if different,
 * both artifacts will be passed to diff_file_artifact() to be diffed.
 */
static int
diff_commit(fsl_buffer *buf, struct fnc_commit_artifact *commit, int diff_flags,
    int context, int sbs, struct fnc_pathlist_head *paths)
{
	fsl_cx			*f = fcli_cx();
	const fsl_card_F	*fc1 = NULL;
	const fsl_card_F	*fc2 = NULL;
	fsl_deck		 d1 = fsl_deck_empty;
	fsl_deck		 d2 = fsl_deck_empty;
	fsl_id_t		 id1;
	int			 different = 0, rc = 0;

	rc = fsl_deck_load_rid(f, &d2, commit->rid, FSL_SATYPE_CHECKIN);
	if (rc)
		goto end;
	rc = fsl_deck_F_rewind(&d2);
	if (rc)
		goto end;

	/*
	 * For the one-and-only special case of repositories, such as the
	 * canonical fnc, that do not have an "initial empty check-in", we
	 * proceed with no parent version to diff against.
	 */
	if (commit->puuid) {
		rc = fsl_sym_to_rid(f, commit->puuid, FSL_SATYPE_CHECKIN, &id1);
		if (rc)
			goto end;
		rc = fsl_deck_load_rid(f, &d1, id1, FSL_SATYPE_CHECKIN);
		if (rc)
			goto end;
		rc = fsl_deck_F_rewind(&d1);
		if (rc)
			goto end;
		fsl_deck_F_next(&d1, &fc1);
	}

	fsl_deck_F_next(&d2, &fc2);
	while (fc1 || fc2) {
		const fsl_card_F	*a = NULL, *b = NULL;
		fsl_ckout_change_e	 change = FSL_CKOUT_CHANGE_NONE;
		bool			 diff = true;

		if (paths != NULL && !TAILQ_EMPTY(paths)) {
			struct fnc_pathlist_entry *pe;
			diff = false;
			TAILQ_FOREACH(pe, paths, entry)
				if (!fsl_strcmp(pe->path, fc1->name) ||
				    !fsl_strcmp(pe->path, fc2->name) ||
				    !fsl_strncmp(pe->path, fc1->name,
				    pe->pathlen) || !fsl_strncmp(pe->path,
				    fc2->name, pe->pathlen)) {
					diff = true;
					break;
				}
		}

		if (!fc1)	/* File added. */
			different = 1;
		else if (!fc2)	/* File deleted. */
			different = -1;
		else		/* Same filename in both versions. */
			different = fsl_strcmp(fc1->name, fc2->name);

		if (different) {
			if (different > 0) {
				b = fc2;
				change = FSL_CKOUT_CHANGE_ADDED;
				fsl_deck_F_next(&d2, &fc2);
			} else if (different < 0) {
				a = fc1;
				change = FSL_CKOUT_CHANGE_REMOVED;
				fsl_deck_F_next(&d1, &fc1);
			}
			if (diff)
				rc = diff_file_artifact(buf, id1, a,
				    commit->rid, b, change, diff_flags,
				    context, sbs, commit->diff_type);
		} else if (!fsl_uuidcmp(fc1->uuid, fc2->uuid)) { /* No change */
			fsl_deck_F_next(&d1, &fc1);
			fsl_deck_F_next(&d2, &fc2);
		} else {
			change = FSL_CKOUT_CHANGE_MOD;
			if (diff)
				rc = diff_file_artifact(buf, id1, fc1,
				    commit->rid, fc2, change, diff_flags,
				    context, sbs, commit->diff_type);
			fsl_deck_F_next(&d1, &fc1);
			fsl_deck_F_next(&d2, &fc2);
		}
		if (rc == FSL_RC_RANGE) {
			fsl_buffer_append(buf,
			    "\nDiff has too many changes\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc == FSL_RC_DIFF_BINARY) {
			fsl_buffer_append(buf,
			    "\nBinary files cannot be diffed\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc)
			goto end;
	}
end:
	fsl_deck_finalize(&d1);
	fsl_deck_finalize(&d2);
	return rc;
}

/*
 * Diff local changes on disk in the current checkout against either a previous
 * commit or, if no version has been supplied, the current checkout.
 *   buf  output buffer in which diff content is appended
 *   vid  repository database record id of the version to diff against
 * diff_flags, context, and sbs are the same parameters as diff_file_artifact()
 * nb. This routine is only called with 'fnc diff [hash]'; that is, one or
 * zero args—not two—supplied to fnc's diff command line interface.
 */
static int
diff_checkout(fsl_buffer *buf, fsl_id_t vid, int diff_flags, int context,
    int sbs, struct fnc_pathlist_head *paths)
{
	fsl_cx		*f = fcli_cx();
	fsl_stmt	*st = NULL;
	fsl_buffer	 sql, abspath, bminus;
	fsl_uuid_str	 xminus = NULL;
	fsl_id_t	 cid;
	int		 rc = 0;
	bool		 allow_symlinks;

	abspath = bminus = sql = fsl_buffer_empty;
	fsl_ckout_version_info(f, &cid, NULL);
	/* cid = fsl_config_get_id(f, FSL_CONFDB_CKOUT, 0, "checkout"); */
	/* XXX Already done in cmd_diff(): Load vfile table with local state. */
	/* rc = fsl_vfile_changes_scan(f, cid, */
	/*     FSL_VFILE_CKSIG_ENOTFILE & FSL_VFILE_CKSIG_KEEP_OTHERS); */
	/* if (rc) */
	/*	return RC(rc, "%s", "fsl_vfile_changes_scan"); */

	/*
	 * If a previous version is supplied, load its vfile state to query
	 * changes. Otherwise query the current checkout state for changes.
	 */
	if (vid != cid) {
		/* Keep vfile ckout state; but unload vid when finished. */
		rc = fsl_vfile_load(f, vid, false, NULL);
		if (rc)
			goto unload;
		fsl_buffer_appendf(&sql, "SELECT v2.pathname, v2.deleted, "
		    "v2.chnged, v2.rid == 0, v1.rid, v1.islink"
		    " FROM vfile v1, vfile v2"
		    " WHERE v1.pathname=v2.pathname AND v1.vid=%d AND v2.vid=%d"
		    " AND (v2.deleted OR v2.chnged OR v1.mrid != v2.rid)"
		    " UNION "
		    "SELECT pathname, 1, 0, 0, 0, islink"
		    " FROM vfile v1"
		    " WHERE v1.vid = %d"
		    " AND NOT EXISTS(SELECT 1 FROM vfile v2"
		    " WHERE v2.vid = %d AND v2.pathname = v1.pathname)"
		    " UNION "
		    "SELECT pathname, 0, 0, 1, 0, islink"
		    " FROM vfile v2"
		    " WHERE v2.vid = %d"
		    " AND NOT EXISTS(SELECT 1 FROM vfile v1"
		    " WHERE v1.vid = %d AND v1.pathname = v2.pathname)"
		    " ORDER BY 1", vid, cid, vid, cid, cid, vid);
	} else {
		fsl_buffer_appendf(&sql, "SELECT pathname, deleted, chnged, "
		    "rid == 0, rid, islink"
		    " FROM vfile"
		    " WHERE vid = %d"
		    " AND (deleted OR chnged OR rid == 0)"
		    " ORDER BY pathname", cid);
	}
	st = fsl_stmt_malloc();
	rc = fsl_cx_prepare(f, st, "%b", &sql);
	if (rc) {
		rc = RC(rc, "%s", "fsl_cx_prepare");
		goto yield;
	}

	while ((rc = fsl_stmt_step(st)) == FSL_RC_STEP_ROW) {
		const char	*path;
		int		 deleted, changed, added, fid, symlink;
		enum		 fsl_ckout_change_e change;
		bool		 diff = true;

		path = fsl_stmt_g_text(st, 0, NULL);
		deleted = fsl_stmt_g_int32(st, 1);
		changed = fsl_stmt_g_int32(st, 2);
		added = fsl_stmt_g_int32(st, 3);
		fid = fsl_stmt_g_int32(st, 4);
		symlink = fsl_stmt_g_int32(st, 5);
		rc = fsl_file_canonical_name2(f->ckout.dir, path, &abspath,
		    false);
		if (rc)
			goto yield;

		if (deleted)
			change = FSL_CKOUT_CHANGE_REMOVED;
		else if (fsl_file_access(fsl_buffer_cstr(&abspath), F_OK))
			change = FSL_CKOUT_CHANGE_MISSING;
		else if (added) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_ADDED;
		} else if (changed == 3) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_MERGE_ADD;
		} else if (changed == 5) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_INTEGRATE_ADD;
		} else
			change = FSL_CKOUT_CHANGE_MOD;

		/*
		 * For changed files of which this checkout is already aware,
		 * grab their hash to make comparisons. For removed files, if
		 * diffing against a version other than the current checkout,
		 * load the version's manifest to parse for known versions of
		 * said files. If we don't, we risk diffing stale or bogus
		 * content. Known cases include MISSING, DELETED, and RENAMED
		 * files, which fossil(1) misses in some instances.
		 */
		if (fid > 0)
			xminus = fsl_rid_to_uuid(f, fid);
		else if (vid != cid && !added) {
			fsl_deck		 d = fsl_deck_empty;
			const fsl_card_F	*cf = NULL;

			rc = fsl_deck_load_rid(f, &d, vid, FSL_SATYPE_CHECKIN);
			if (!rc)
				rc = fsl_deck_F_rewind(&d);
			if (rc)
				goto yield;
			do {
				fsl_deck_F_next(&d, &cf);
				if (cf && !fsl_strcmp(cf->name, path)) {
					xminus = fsl_strdup(cf->uuid);
					if (xminus == NULL) {
						RC(FSL_RC_ERROR, "%s",
						    "fsl_strdup");
						goto yield;
					}
					fid = fsl_uuid_to_rid(f, xminus);
					break;
				}
			} while (cf);
			fsl_deck_finalize(&d);
		}
		if (!xminus)
			xminus = fsl_strdup(NULL_DEVICE);
		allow_symlinks = fsl_config_get_bool(f, FSL_CONFDB_REPO, false,
		    "allow-symlinks");
		if (!symlink != !(fsl_is_symlink(fsl_buffer_cstr(&abspath)) &&
		    allow_symlinks)) {
			rc = write_diff_meta(buf, path, xminus, path,
			    NULL_DEVICE, diff_flags, change);
			fsl_buffer_append(buf, "\nSymbolic links and regular "
			    "files cannot be diffed\n", -1);
			if (rc)
				goto yield;
			continue;
		}
		if (fid > 0 && change != FSL_CKOUT_CHANGE_ADDED) {
			rc = fsl_content_get(f, fid, &bminus);
			if (rc)
				goto yield;
		} else
			fsl_buffer_clear(&bminus);
		if (paths != NULL && !TAILQ_EMPTY(paths)) {
			struct fnc_pathlist_entry *pe;
			diff = false;
			TAILQ_FOREACH(pe, paths, entry)
				if (!fsl_strncmp(pe->path, path, pe->pathlen)
				    || !fsl_strcmp(pe->path, path)) {
					diff = true;
					break;
				}
		}
		if (diff)
			rc = diff_file(buf, &bminus, path, xminus,
			    fsl_buffer_cstr(&abspath), change, diff_flags,
			    context, sbs);
		fsl_buffer_reuse(&bminus);
		fsl_buffer_reuse(&abspath);
		fsl_free(xminus);
		xminus = NULL;
		if (rc == FSL_RC_RANGE) {
			fsl_buffer_append(buf,
			    "\nDiff has too many changes\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc == FSL_RC_DIFF_BINARY) {
			fsl_buffer_append(buf,
			    "\nBinary files cannot be diffed\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc)
			goto yield;
	}

yield:
	fsl_stmt_finalize(st);
	fsl_free(xminus);
unload:
	fsl_vfile_unload_except(f, cid);
	fsl_buffer_clear(&abspath);
	fsl_buffer_clear(&bminus);
	fsl_buffer_clear(&sql);
	return rc;
}

/*
 * Write diff index line and file metadata (i.e., file paths and hashes), which
 * signify file addition, removal, or modification.
 *   buf         output buffer in which diff output will be appended
 *   zminus      file name of the file being diffed against
 *   xminus      hex hash of file named zminus
 *   zplus       file name of the file being diffed
 *   xplus       hex hash of the file named zplus
 *   diff_flags  bitwise flags to control the diff
 *   change      enum denoting the versioning change of the file
 */
static int
write_diff_meta(fsl_buffer *buf, const char *zminus, fsl_uuid_str xminus,
    const char *zplus, fsl_uuid_str xplus, int diff_flags,
    enum fsl_ckout_change_e change)
{
	int	rc = 0;
	const char	*index, *plus, *minus;

	index = zplus ? zplus : (zminus ? zminus : NULL_DEVICE);

	switch (change) {
	case FSL_CKOUT_CHANGE_MERGE_ADD:
		/* FALL THROUGH */
	case FSL_CKOUT_CHANGE_INTEGRATE_ADD:
		/* FALL THROUGH */
	case FSL_CKOUT_CHANGE_ADDED:
		minus = NULL_DEVICE;
		plus = xplus;
		zminus = NULL_DEVICE;
		break;
	case FSL_CKOUT_CHANGE_MISSING:
		/* FALL THROUGH */
	case FSL_CKOUT_CHANGE_REMOVED:
		minus = xminus;
		plus = NULL_DEVICE;
		zplus = NULL_DEVICE;
		break;
	case FSL_CKOUT_CHANGE_RENAMED:
		/* FALL THROUGH */
	case FSL_CKOUT_CHANGE_MOD:
		/* FALL THROUGH */
	default:
		minus = xminus;
		plus = xplus;
		break;
	}

	if (diff_flags & FSL_DIFF_INVERT) {
		const char *tmp = minus;
		minus = plus;
		plus = tmp;
		tmp = zminus;
		zminus = zplus;
		zplus = tmp;
	}

	if ((diff_flags & (FSL_DIFF_SIDEBYSIDE | FSL_DIFF_BRIEF)) == 0) {
		rc = fsl_buffer_appendf(buf, "\nIndex: %s\n%.71c\n", index, '=');
		if (!rc)
			rc = fsl_buffer_appendf(buf, "hash - %s\nhash + %s\n",
			    minus, plus);
	}
	if (!rc && (diff_flags & FSL_DIFF_BRIEF) == 0)
		rc = fsl_buffer_appendf(buf, "--- %s\n+++ %s\n", zminus, zplus);

	return rc;
}

/*
 * The diff_file_artifact() counterpart that diffs actual files on disk rather
 * than file artifacts in the Fossil repository's blob table.
 *   buf      output buffer in which diff output will be appended
 *   bminus   blob containing content of the versioned file being diffed against
 *   zminus   filename of bminus
 *   xminus   hex UUID containing the SHA{1,3} hash of the file named zminus
 *   abspath  absolute path to the file on disk being diffed
 *   change   enum denoting the versioning change of the file
 * diff_flags, context, and sbs are the same parameters as diff_file_artifact()
 */
static int
diff_file(fsl_buffer *buf, fsl_buffer *bminus, const char *zminus,
    fsl_uuid_str xminus, const char *abspath, enum fsl_ckout_change_e change,
    int diff_flags, int context, bool sbs)
{
	fsl_cx		*f = fcli_cx();
	fsl_buffer	 bplus = fsl_buffer_empty;
	fsl_buffer	 xplus = fsl_buffer_empty;
	const char	*zplus = NULL;
	int		 rc = 0;
	bool		 verbose;

	/*
	 * If it exists, read content of abspath to diff EXCEPT for the content
	 * of 'fossil rm FILE' files because they will either: (1) have the same
	 * content as the versioned file's blob in bminus or (2) have changes.
	 * As a result, the upcoming call to fsl_diff_text_to_buffer() _will_
	 * (1) produce an empty diff or (2) show the differences; neither are
	 * expected behaviour because the SCM has been instructed to remove the
	 * file; therefore, the diff should display the versioned file content
	 * as being entirely removed. With this check, fnc now contrasts the
	 * behaviour of fossil(1), which produces the abovementioned unexpected
	 * output described in (1) and (2).
	 */
	if (change != FSL_CKOUT_CHANGE_REMOVED) {
		rc = fsl_ckout_file_content(f, false, abspath, &bplus);
		if (rc)
			goto end;
		/*
		 * To replicate fossil(1)'s behaviour—where a fossil rm'd file
		 * will either show as an unchanged or edited rather than a
		 * removed file with 'fossil diff -v' output—remove the above
		 * 'if (change != FSL_CKOUT_CHANGE_REMOVED)' from the else
		 * condition and uncomment the following three lines of code.
		 */
		/* if (change == FSL_CKOUT_CHANGE_REMOVED && */
		/*     !fsl_buffer_compare(bminus, &bplus)) */
		/*	fsl_buffer_clear(&bplus); */
		zplus = zminus;
	}

	switch (fsl_strlen(xminus)) {
	case FSL_STRLEN_K256:
		rc = fsl_sha3sum_buffer(&bplus, &xplus);
		break;
	case FSL_STRLEN_SHA1:
		rc = fsl_sha1sum_buffer(&bplus, &xplus);
		break;
	case NULL_DEVICELEN:
		switch (fsl_config_get_int32(f, FSL_CONFDB_REPO,
		    FSL_HPOLICY_AUTO, "hash-policy")) {
		case FSL_HPOLICY_SHA1:
			rc = fsl_sha1sum_buffer(&bplus, &xplus);
			break;
		case FSL_HPOLICY_AUTO:
			/* FALL THROUGH */
		case FSL_HPOLICY_SHA3:
			/* FALL THROUGH */
		case FSL_HPOLICY_SHA3_ONLY:
			rc = fsl_sha3sum_buffer(&bplus, &xplus);
			break;
		}
		break;
	default:
		RC(FSL_RC_SIZE_MISMATCH, "invalid artifact uuid [%s]", xminus);
		goto end;
	}
	if (rc)
		goto end;

	rc = write_diff_meta(buf, zminus, xminus, zplus, fsl_buffer_str(&xplus),
	    diff_flags, change);
	if (rc)
		goto end;

	verbose = (diff_flags & FSL_DIFF_VERBOSE) != 0 ? true : false;
	if (diff_flags & FSL_DIFF_BRIEF) {
		rc = fsl_buffer_compare(bminus, &bplus);
		if (!rc)
			rc = fsl_buffer_appendf(buf, "CHANGED -> %s\n", zminus);
	} else if (verbose || (bminus->used && bplus.used)) {
		rc = fsl_diff_text_to_buffer(bminus, &bplus, buf, context,
		    sbs, diff_flags);
	}

end:
	fsl_buffer_clear(&bplus);
	fsl_buffer_clear(&xplus);

	return rc;
}

/*
 * Parse the deck of non-checkin commits to present a 'fossil ui' equivalent
 * of the corresponding artifact when selected from the timeline.
 * TODO: Rename this horrible function name.
 */
static int
diff_non_checkin(fsl_buffer *buf, struct fnc_commit_artifact *commit,
    int diff_flags, int context, int sbs)
{
	fsl_cx		*f = fcli_cx();
	fsl_buffer	 wiki = fsl_buffer_empty;
	fsl_buffer	 pwiki = fsl_buffer_empty;
	fsl_id_t	 prid = 0;
	fsl_size_t	 idx;
	int		 rc = 0;

	fsl_deck *d = NULL;
	d = fsl_deck_malloc();
	if (d == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_deck_malloc");

	fsl_deck_init(f, d, FSL_SATYPE_ANY);
	if ((rc = fsl_deck_load_rid(f, d, commit->rid, FSL_SATYPE_ANY)))
		goto end;

	/*
	 * Present ticket commits as a series of field: value tuples as per
	 * the Fossil UI /info/UUID view.
	 */
	if (d->type == FSL_SATYPE_TICKET) {
		for (idx = 0; idx < d->J.used; ++idx) {
			fsl_card_J *ticket = d->J.list[idx];
			bool icom = !fsl_strncmp(ticket->field, "icom", 4);
			fsl_buffer_appendf(buf, "%d. %s:%s%s%c\n", idx + 1,
			    ticket->field, icom ? "\n\n" : " ", ticket->value,
			    icom ? '\n' : ' ');
		}
		goto end;
	}

	if (d->type == FSL_SATYPE_CONTROL) {
		for (idx = 0; idx < d->T.used; ++idx) {
			fsl_card_T *ctl = d->T.list[idx];
			fsl_buffer_appendf(buf, "Tag %d ", idx + 1);
			switch (ctl->type) {
			case FSL_TAGTYPE_CANCEL:
				fsl_buffer_append(buf, "[CANCEL]", -1);
				break;
			case FSL_TAGTYPE_ADD:
				fsl_buffer_append(buf, "[ADD]", -1);
				break;
			case FSL_TAGTYPE_PROPAGATING:
				fsl_buffer_append(buf, "[PROPAGATE]", -1);
				break;
			default:
				break;
			}
			if (ctl->uuid)
				fsl_buffer_appendf(buf, "\ncheckin %s",
				    ctl->uuid);
			fsl_buffer_appendf(buf, "\n%s", ctl->name);
			if (!fsl_strcmp(ctl->name, "branch"))
				commit->branch = fsl_strdup(ctl->value);
			if (ctl->value)
				fsl_buffer_appendf(buf, " -> %s", ctl->value);
			fsl_buffer_append(buf, "\n\n", 2);
		}
		goto end;
	}
	/*
	 * If neither a ticket nor control artifact, we assume it's a wiki, so
	 * check if it has a parent commit to diff against. If not, append the
	 * entire wiki card content.
	 */
	fsl_buffer_append(&wiki, d->W.mem, d->W.used);
	if (commit->puuid == NULL) {
		if (d->P.used > 0)
			commit->puuid = fsl_strdup(d->P.list[0]);
		else {
			fsl_buffer_copy(&wiki, buf);
			goto end;
		}
	}

	/* Diff the artifacts if a parent is found. */
	if ((rc = fsl_sym_to_rid(f, commit->puuid, FSL_SATYPE_ANY, &prid)))
		goto end;
	if ((rc = fsl_deck_load_rid(f, d, prid, FSL_SATYPE_ANY)))
		goto end;
	fsl_buffer_append(&pwiki, d->W.mem, d->W.used);

	rc = fsl_diff_text_to_buffer(&pwiki, &wiki, buf, context, sbs,
	    diff_flags);

	/* If a technote, provide the full content after its diff. */
	if (d->type == FSL_SATYPE_TECHNOTE)
		fsl_buffer_appendf(buf, "\n---\n\n%s", wiki.mem);

end:
	fsl_buffer_clear(&wiki);
	fsl_buffer_clear(&pwiki);
	fsl_deck_finalize(d);
	return rc;
}

/*
 * Compute the differences between two repository file artifacts to produce the
 * set of changes necessary to convert one into the other.
 *   buf         output buffer in which diff output will be appended
 *   vid1        repo record id of the version from which artifact a belongs
 *   a           file artifact being diffed against
 *   vid2        repo record id of the version from which artifact b belongs
 *   b           file artifact being diffed
 *   change      enum denoting the versioning change of the file
 *   diff_flags  bitwise flags to control the diff
 *   context     the number of context lines to surround changes
 *   sbs	 number of columns in which to display each side-by-side diff
 */
static int
diff_file_artifact(fsl_buffer *buf, fsl_id_t vid1, const fsl_card_F *a,
    fsl_id_t vid2, const fsl_card_F *b, enum fsl_ckout_change_e change,
    int diff_flags, int context, int sbs, enum fnc_diff_type diff_type)
{
	fsl_cx		*f = fcli_cx();
	fsl_stmt	 stmt = fsl_stmt_empty;
	fsl_buffer	 fbuf1 = fsl_buffer_empty;
	fsl_buffer	 fbuf2 = fsl_buffer_empty;
	char		*zminus0 = NULL, *zplus0 = NULL;
	const char	*zplus = NULL, *zminus = NULL;
	fsl_uuid_str	 xplus0 = NULL, xminus0 = NULL;
	fsl_uuid_str	 xplus = NULL, xminus = NULL;
	int		 rc = 0;
	bool		 verbose;

	assert(vid1 != vid2);
	assert(vid2 > 0 &&
	    "local checkout should be diffed with diff_checkout()");

	fbuf2.used = fbuf1.used = 0;

	if (a) {
		rc = fsl_card_F_content(f, a, &fbuf1);
		if (rc)
			goto end;
		zminus = a->name;
		xminus = a->uuid;
	} else if (diff_type == FNC_DIFF_BLOB) {
		rc = fsl_cx_prepare(f, &stmt,
		    "SELECT name FROM filename, mlink "
		    "WHERE filename.fnid=mlink.fnid AND mlink.fid = %d", vid1);
		if (rc) {
			rc = RC(FSL_RC_DB, "%s %d", "fsl_cx_prepare", vid1);
			goto end;
		}
		rc = fsl_stmt_step(&stmt);
		if (rc == FSL_RC_STEP_ROW) {
			rc = 0;
			zminus0 = fsl_strdup(fsl_stmt_g_text(&stmt, 0, NULL));
			zminus = zminus0;
		} else if (rc == FSL_RC_STEP_DONE)
			rc = 0;
		else if (rc) {
			rc = RC(rc, "%s", "fsl_stmt_step");
			goto end;
		}
		xminus0 = fsl_rid_to_uuid(f, vid1);
		xminus = xminus0;
		fsl_stmt_finalize(&stmt);
		fsl_content_get(f, vid1, &fbuf1);
	}
	if (b) {
		rc = fsl_card_F_content(f, b, &fbuf2);
		if (rc)
			goto end;
		zplus = b->name;
		xplus = b->uuid;
	} else if (diff_type == FNC_DIFF_BLOB) {
		rc = fsl_cx_prepare(f, &stmt,
		    "SELECT name FROM filename, mlink "
		    "WHERE filename.fnid=mlink.fnid AND mlink.fid = %d", vid2);
		if (rc) {
			rc = RC(FSL_RC_DB, "%s %d", "fsl_cx_prepare", vid2);
			goto end;
		}
		rc = fsl_stmt_step(&stmt);
		if (rc == FSL_RC_STEP_ROW) {
			rc = 0;
			zplus0 = fsl_strdup(fsl_stmt_g_text(&stmt, 0, NULL));
			zplus = zplus0;
		} else if (rc == FSL_RC_STEP_DONE)
			rc = 0;
		else if (rc) {
			rc = RC(rc, "%s", "fsl_stmt_step");
			goto end;
		}
		xplus0 = fsl_rid_to_uuid(f, vid2);
		xplus = xplus0;
		fsl_stmt_finalize(&stmt);
		fsl_content_get(f, vid2, &fbuf2);
	}

	rc = write_diff_meta(buf, zminus, xminus, zplus, xplus, diff_flags,
	    change);
	verbose = (diff_flags & FSL_DIFF_VERBOSE) != 0 ? true : false;
	if (verbose || (a && b))
		rc = fsl_diff_text_to_buffer(&fbuf1, &fbuf2, buf, context, sbs,
		    diff_flags);
	if (rc)
		RC(rc, "%s: fsl_diff_text_to_buffer\n"
		    " -> %s [%s]\n -> %s [%s]", fsl_rc_cstr(rc),
		    a ? a->name : NULL_DEVICE, a ? a->uuid : NULL_DEVICE,
		    b ? b->name : NULL_DEVICE, b ? b->uuid : NULL_DEVICE);
end:
	fsl_free(zminus0);
	fsl_free(zplus0);
	fsl_free(xminus0);
	fsl_free(xplus0);
	fsl_buffer_clear(&fbuf1);
	fsl_buffer_clear(&fbuf2);
	return rc;
}

static int
show_diff(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	char				*headln, *id2, *id1 = NULL;

	/* Some diffs (e.g., technote, tag) have no parent hash to display. */
	id1 = fsl_strdup(s->id1 ? s->id1 : "/dev/null");
	if (id1 == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");

	/*
	 * If diffing the work tree, we have no hash to display for it.
	 * XXX Display "work tree" or "checkout" or "/dev/null" for clarity?
	 */
	id2 = fsl_strdup(s->id2 ? s->id2 : "");
	if (id2 == NULL) {
		fsl_free(id1);
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	}

	if ((headln = fsl_mprintf("diff %.40s %.40s", id1, id2)) == NULL) {
		fsl_free(id1);
		fsl_free(id2);
		return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
	}

	fsl_free(id1);
	fsl_free(id2);
	return write_diff(view, headln);
}

static int
write_diff(struct fnc_view *view, char *headln)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	regmatch_t			*regmatch = &view->regmatch;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	char				*line;
	size_t				 linesz = 0;
	ssize_t				 linelen;
	off_t				 line_offset;
	int				 wstrlen;
	int				 max_lines = view->nlines;
	int				 nlines = s->nlines;
	int				 rc = 0, nprintln = 0;
	int				 match = -1;

	line_offset = s->line_offsets[s->first_line_onscreen - 1];
	if (fseeko(s->f, line_offset, SEEK_SET))
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "fseeko");

	werase(view->window);

	if (headln) {
		if ((line = fsl_mprintf("[%d/%d] %s", (s->first_line_onscreen -
		    1 + s->current_line), nlines, headln)) == NULL)
			return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0);
		fsl_free(line);
		fsl_free(headln);
		if (rc)
			return rc;

		if (screen_is_shared(view))
			wstandout(view->window);
		waddwstr(view->window, wcstr);
		fsl_free(wcstr);
		wcstr = NULL;
		if (screen_is_shared(view))
			wstandend(view->window);
		if (wstrlen <= view->ncols - 1)
			waddch(view->window, '\n');

		if (max_lines <= 1)
			return rc;
		--max_lines;
	}

	s->eof = false;
	line = NULL;
	while (max_lines > 0 && nprintln < max_lines) {
		linelen = getline(&line, &linesz, s->f);
		if (linelen == -1) {
			if (feof(s->f)) {
				s->eof = true;
				break;
			}
			fsl_free(line);
			RC(ferror(s->f) ? fsl_errno_to_rc(errno, FSL_RC_IO) :
			    FSL_RC_IO, "%s", "getline");
			return rc;
		}

		if (s->colour && (match = fsl_list_index_of(&s->colours, line,
		    match_line)) != -1)
			c = s->colours.list[match];
		if (c)
			wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
		if (s->first_line_onscreen + nprintln == s->matched_line &&
		    regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
			rc = write_matched_line(&wstrlen, line, view->ncols, 0,
			    view->window, regmatch);
			if (rc) {
				fsl_free(line);
				return rc;
			}
		} else {
			rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0);
			if (rc) {
				fsl_free(line);
				return rc;
			}
			waddwstr(view->window, wcstr);
			fsl_free(wcstr);
			wcstr = NULL;
		}
		if (c) {
			wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
			c = NULL;
		}
		if (wstrlen <= view->ncols - 1)
			waddch(view->window, '\n');
		++nprintln;
	}
	fsl_free(line);
	if (nprintln >= 1)
		s->last_line_onscreen = s->first_line_onscreen + (nprintln - 1);
	else
		s->last_line_onscreen = s->first_line_onscreen;

	draw_vborder(view);

	if (s->eof) {
		while (nprintln < view->nlines) {
			waddch(view->window, '\n');
			++nprintln;
		}

		wstandout(view->window);
		waddstr(view->window, "(END)");
		wstandend(view->window);
	}

	return rc;
}

static int
match_line(const void *ln, const void *key)
{
	struct fnc_colour *c = (struct fnc_colour *)key;
	const char *line = ln;

	return regexec(&c->regex, line, 0, NULL, 0);
}

static bool
screen_is_shared(struct fnc_view *view)
{
	if (view_is_parent(view)) {
		if (view->child == NULL || view->child->active ||
		    !screen_is_split(view->child))
			return false;
	} else if (!screen_is_split(view))
		return false;

	return view->active;
}

static int
view_is_parent(struct fnc_view *view)
{
	return view->parent == NULL;
}

static int
screen_is_split(struct fnc_view *view)
{
	return view->start_col > 0;
}

static int
write_matched_line(int *col_pos, const char *line, int ncols_avail,
    int start_column, WINDOW *window, regmatch_t *regmatch)
{
	wchar_t		*wcstr;
	char		*s;
	int		 wstrlen;
	int		 rc = 0;

	*col_pos = 0;

	/* Copy the line up to the matching substring & write it to screen. */
	s = fsl_strndup(line, regmatch->rm_so);
	if (s == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strndup");

	rc = formatln(&wcstr, &wstrlen, s, ncols_avail, start_column);
	if (rc) {
		free(s);
		return rc;
	}
	waddwstr(window, wcstr);
	free(wcstr);
	free(s);
	ncols_avail -= wstrlen;
	*col_pos += wstrlen;

	/* If not EOL, copy matching string & write to screen with highlight. */
	if (ncols_avail > 0) {
		s = fsl_strndup(line + regmatch->rm_so,
		    regmatch->rm_eo - regmatch->rm_so);
		if (s == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strndup");
			free(s);
			return rc;
		}
		rc = formatln(&wcstr, &wstrlen, s, ncols_avail, start_column);
		if (rc) {
			free(s);
			return rc;
		}
		wattr_on(window, A_REVERSE, NULL);
		waddwstr(window, wcstr);
		wattr_off(window, A_REVERSE, NULL);
		free(wcstr);
		free(s);
		ncols_avail -= wstrlen;
		*col_pos += wstrlen;
	}

	/* Write the rest of the line if not yet at EOL. */
	if (ncols_avail > 0 && fsl_strlen(line) > (fsl_size_t)regmatch->rm_eo) {
		rc = formatln(&wcstr, &wstrlen, line + regmatch->rm_eo,
		    ncols_avail, start_column);
		if (rc)
			return rc;
		waddwstr(window, wcstr);
		free(wcstr);
		*col_pos += wstrlen;
	}

	return rc;
}

static void
draw_vborder(struct fnc_view *view)
{
	const struct fnc_view	*view_above;
	char			*codeset = nl_langinfo(CODESET);
	PANEL			*panel;

	if (view->parent)
		draw_vborder(view->parent);

	panel = panel_above(view->panel);
	if (panel == NULL)
		return;

	view_above = panel_userptr(panel);
	mvwvline(view->window, view->start_ln, view_above->start_col - 1,
	    (strcmp(codeset, "UTF-8") == 0) ? ACS_VLINE : '|', view->nlines);
#ifdef __linux__
	wnoutrefresh(view->window);
#endif
}

static int
diff_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	struct fnc_tl_view_state	*tlstate;
	struct commit_entry		*previous_selection;
	char				*line = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 i, rc = 0;
	bool				 tl_down = false;

	switch (ch) {
	case KEY_DOWN:
	case 'j':
		if (!s->eof)
			++s->first_line_onscreen;
		break;
	case KEY_NPAGE:
	case CTRL('f'):
	case ' ':
		if (s->eof)
			break;
		i = 0;
		while (!s->eof && i++ < view->nlines - 1) {
			linelen = getline(&line, &linesz, s->f);
			++s->first_line_onscreen;
			if (linelen == -1) {
				if (feof(s->f))
					s->eof = true;
				else
					RC(ferror(s->f) ?
					    fsl_errno_to_rc(errno, FSL_RC_IO) :
					    FSL_RC_IO, "%s", "getline");
				break;
			}
		}
		free(line);
		break;
	case KEY_END:
	case 'G':
		if (s->eof)
			break;
		s->first_line_onscreen = (s->nlines - view->nlines) + 2;
		s->eof = true;
		break;
	case KEY_UP:
	case 'k':
		if (s->first_line_onscreen > 1)
			--s->first_line_onscreen;
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->first_line_onscreen == 1)
			break;
		i = 0;
		while (i++ < view->nlines - 1 && s->first_line_onscreen > 1)
			--s->first_line_onscreen;
		break;
	case 'g':
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	case KEY_HOME:
		s->first_line_onscreen = 1;
		break;
	case 'c':
	case 'i':
	case 'v':
	case 'w':
		if (ch == 'c')
			s->colour = !s->colour;
		if (ch == 'i')
			s->diff_flags ^= FSL_DIFF_INVERT;
		if (ch == 'v')
			s->diff_flags ^= FSL_DIFF_VERBOSE;
		if (ch == 'w')
			s->diff_flags ^= FSL_DIFF_IGNORE_ALLWS;
		wclear(view->window);
		s->first_line_onscreen = 1;
		s->last_line_onscreen = view->nlines;
		show_diff_status(view);
		rc = create_diff(s);
		break;
	case '-':
	case '_':
		if (s->context > 0) {
			--s->context;
			show_diff_status(view);
			rc = create_diff(s);
			if (s->first_line_onscreen + view->nlines - 1 >
			    (int)s->nlines) {
				s->first_line_onscreen = 1;
				s->last_line_onscreen = view->nlines;
			}
		}
		break;
	case '+':
	case '=':
		if (s->context < DIFF_MAX_CTXT) {
			++s->context;
			show_diff_status(view);
			rc = create_diff(s);
		}
		break;
	case CTRL('j'):
	case '>':
	case '.':
	case 'J':
		tl_down = true;
		/* FALL THROUGH */
	case CTRL('k'):
	case '<':
	case ',':
	case 'K':
		if (s->timeline_view == NULL)
			break;
		tlstate = &s->timeline_view->state.timeline;
		previous_selection = tlstate->selected_commit;

		if ((rc = tl_input_handler(NULL, s->timeline_view,
		    tl_down ? KEY_DOWN : KEY_UP)))
			break;

		if (previous_selection == tlstate->selected_commit)
			break;

		if ((rc = set_selected_commit(s, tlstate->selected_commit)))
			break;

		s->first_line_onscreen = 1;
		s->last_line_onscreen = view->nlines;

		show_diff_status(view);
		rc = create_diff(s);
		break;
	default:
		break;
	}

	return rc;
}

static int
set_selected_commit(struct fnc_diff_view_state *s, struct commit_entry *entry)
{
	fsl_free(s->id2);
	s->id2 = fsl_strdup(entry->commit->uuid);
	if (s->id2 == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	fsl_free(s->id1);
	s->id1 = entry->commit->puuid ? fsl_strdup(entry->commit->puuid) : NULL;
	s->selected_commit = entry->commit;

	return 0;
}

static int
diff_search_init(struct fnc_view *view)
{
	struct fnc_diff_view_state *s = &view->state.diff;

	s->matched_line = 0;
	return 0;
}

static int
diff_search_next(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	char				*line = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 start_ln;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
		return 0;
	}

	if (s->matched_line) {
		if (view->searching == SEARCH_FORWARD)
			start_ln = s->matched_line + 1;
		else
			start_ln = s->matched_line - 1;
	} else {
		if (view->searching == SEARCH_FORWARD)
			start_ln = 1;
		else
			start_ln = s->nlines;
	}

	while (1) {
		off_t offset;

		if (start_ln <= 0 || start_ln > (int)s->nlines) {
			if (s->matched_line == 0) {
				view->search_status = SEARCH_CONTINUE;
				break;
			}

			if (view->searching == SEARCH_FORWARD)
				start_ln = 1;
			else
				start_ln = s->nlines;
		}

		offset = s->line_offsets[start_ln - 1];
		if (fseeko(s->f, offset, SEEK_SET) != 0) {
			free(line);
			return RC(fsl_errno_to_rc(errno, FSL_RC_IO),
			    "%s", "fseeko");
		}
		linelen = getline(&line, &linesz, s->f);
		if (linelen != -1 && regexec(&view->regex, line, 1,
		    &view->regmatch, 0) == 0) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_line = start_ln;
			break;
		}
		if (view->searching == SEARCH_FORWARD)
			++start_ln;
		else
			--start_ln;
	}
	free(line);

	if (s->matched_line) {
		s->first_line_onscreen = s->matched_line;
		s->current_line = 1;
	}

	return 0;
}

static int
close_diff_view(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	struct fsl_list_state		st = { FNC_COLOUR_OBJ };
	int				 rc = 0;

	if (s->f && fclose(s->f) == EOF)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");
	fsl_free(s->id1);
	s->id1 = NULL;
	fsl_free(s->id2);
	s->id2 = NULL;
	fsl_free(s->line_offsets);
	fsl_list_clear(&s->colours, fsl_list_object_free, &st);
	s->line_offsets = NULL;
	s->nlines = 0;
	return rc;
}

static void
fnc_resizeterm(void)
{
	struct winsize	size;
	int		cols, lines;

	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
		cols = 80;
		lines = 24;
	} else {
		cols = size.ws_col;
		lines = size.ws_row;
	}
	resize_term(lines, cols);
}

static int
view_resize(struct fnc_view *view)
{
	int	 nlines, ncols;

	if (view->lines > LINES)
		nlines = view->nlines - (view->lines - LINES);
	else
		nlines = view->nlines + (LINES - view->lines);

	if (view->cols > COLS)
		ncols = view->ncols - (view->cols - COLS);
	else
		ncols = view->ncols + (COLS - view->cols);

	if (wresize(view->window, nlines, ncols) == ERR)
		return RC(FSL_RC_ERROR, "%s", "wresize");
	if (replace_panel(view->panel, view->window) == ERR)
		return RC(FSL_RC_ERROR, "%s", "replace_panel");
	wclear(view->window);

	view->nlines = nlines;
	view->ncols = ncols;
	view->lines = LINES;
	view->cols = COLS;

	if (view->child) {
		view->child->start_col = view_split_start_col(view->start_col);
		if (view->child->start_col == 0) {
			make_fullscreen(view->child);
			if (view->child->active)
				show_panel(view->child->panel);
			else
				show_panel(view->panel);
		} else {
			make_splitscreen(view->child);
			show_panel(view->child->panel);
		}
	}

	return 0;
}

/*
 * Consume repeatable arguments containing artifact type values used in
 * constructing the SQL query to generate commit records of the specified
 * type for the timeline. TODO: Enhance this to generalise processing of
 * various repeatable arguments--paths, usernames, branches, etc.--so we
 * can filter on multiples of these values.
 */
static int
fcli_flag_type_arg_cb(fcli_cliflag const *v)
{
	if (fnc_init.filter_types->nitems)
		fnc_init.filter_types->values =
		    fsl_realloc(fnc_init.filter_types->values,
		    (fnc_init.filter_types->nitems + 1) * sizeof(char *));
	fnc_init.filter_types->values[fnc_init.filter_types->nitems++] =
	    *((const char **)v->flagValue);

	return FCLI_RC_FLAG_AGAIN;
}

static void
sigwinch_handler(int sig)
{
	if (sig == SIGWINCH) {
		struct winsize winsz;

		ioctl(0, TIOCGWINSZ, &winsz);
		rec_sigwinch = 1;
	}
}

static void
sigpipe_handler(int sig)
{
	struct sigaction	sact;
	int			e;

	rec_sigpipe = 1;
	memset(&sact, 0, sizeof(sact));
	sact.sa_handler = SIG_IGN;
	sact.sa_flags = SA_RESTART;
	e = sigaction(SIGPIPE, &sact, NULL);
	if (e)
		err(1, "SIGPIPE");
}

static void
sigcont_handler(int sig)
{
	rec_sigcont = 1;
}

__dead static void
usage(void)
{
	/*
	 * It looks like the fsl_cx f member of the ::fcli singleton has
	 * already been cleaned up by the time this wrapper is called from
	 * fcli_help() after hijacking the process whenever the '--help'
	 * argument is passsed on the command line, so we can't use the
	 * f->output fsl_outputer implementation as we would like.
	 */
	/* fsl_cx *f = fcli_cx(); */
	/* f->output = fsl_outputer_FILE; */
	/* f->output.state.state = (fnc_init.err == true) ? stderr : stdout; */
        FILE *f = fnc_init.err ? stderr : stdout;
	size_t idx = 0;

	endwin();

	/* If a command was passed on the CLI, output its corresponding help. */
	if (fnc_init.cmdarg)
		for (idx = 0; idx < nitems(fnc_init.cmd_args); ++idx) {
			fcli_command cmd = fnc_init.cmd_args[idx];
			if (!fsl_strcmp(fnc_init.cmdarg, cmd.name) ||
			    fcli_cmd_aliascmp(&cmd, fnc_init.cmdarg)) {
				fcli_command_help(&cmd, true, true);
				exit(fcli_end_of_main(fnc_init.err));
			}
		}

	/* Otherwise, output help/usage for all commands. */
	fcli_command_help(fnc_init.cmd_args, true, false);
	fsl_fprintf(f, "  note: %s "
	    "with no args defaults to the timeline command.\n\n",
	    fcli_progname());

	exit(fcli_end_of_main(fnc_init.err));
}

static void
usage_timeline(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s timeline [-C|--no-colour] [-T tag] [-b branch] "
	    "[-c commit] [-h|--help] [-n n] [-t type] [-u user] [-z|--utc] "
	    "[path]\n"
	    "  e.g.: %s timeline --type ci -u jimmy src/frobnitz.c\n\n",
	    fcli_progname(), fcli_progname());
}

static void
usage_diff(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s diff [-C|--no-colour] [-h|--help] [-i|--invert]"
	    " [-q|--quiet] [-w|--whitespace] [-x|--context n] "
	    "[artifact1 [artifact2]] [path ...]\n  "
	    "e.g.: %s diff --context 3 d34db33f c0ff33 src/*.c\n\n",
	    fcli_progname(), fcli_progname());
}

static void
usage_tree(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s tree [-C|--no-colour] [-c commit] [-h|--help] [path]\n"
	    "  e.g.: %s tree -c d34dc0d3\n\n" ,
	    fcli_progname(), fcli_progname());
}

static void
usage_blame(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s blame [-C|--no-colour] [-c commit [-r]] [-h|--help] "
	    "[-n n] path\n"
	    "  e.g.: %s blame -c d34db33f src/foo.c\n\n" ,
	    fcli_progname(), fcli_progname());
}

static void
usage_branch(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s branch [-C|--no-colour] [-a|--after date] "
	    "[-b|--before date] [-c|--closed] [-h|--help] [-o|--open] "
	    "[-p|--no-private] [-r|--reverse] [-s|--sort order] [glob]\n"
	    "  e.g.: %s branch -b 2020-10-10\n\n" ,
	    fcli_progname(), fcli_progname());
}

static int
cmd_diff(fcli_command const *argv)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_view			*view;
	struct fnc_commit_artifact	*commit = NULL;
	struct fnc_pathlist_head	 paths;
	struct fnc_pathlist_entry	*pe;
	fsl_deck			 d = fsl_deck_empty;
	fsl_stmt			*q = NULL;
	const char			*artifact1 = NULL, *artifact2 = NULL;
	char				*path0 = NULL;
	fsl_id_t			 prid = -1, rid = -1;
	int				 context = DIFF_DEF_CTXT, rc = 0;
	unsigned short			 blob = 0;
	enum fnc_diff_type		 diff_type;
	bool				 showmeta = false;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	TAILQ_INIT(&paths);

	/*
	 * To provide an intuitive UI, use some magic. First, if there's an arg
	 * and it's a symbolic checkin name, take as a checkin artifact. Repeat
	 * for the next arg. If just one is a checkin, diff changes on disk
	 * against it. If neither are checkins, diff changes on disk against the
	 * current checkout. If both are checkins, diff against eachother. Treat
	 * any non-symbol args as paths and try map to a valid repo path or F
	 * card in the checkin(s) deck(s). It's tricky, but provides a smart UI:
	 * fnc diff f1 f2 ... -> diff f{1,2,...} on disk against current ckout
	 * fnc diff sym3 f1 -> diff f1 on disk against f1 found in checkin sym3
	 * fnc diff sym1 sym2 f1 f2 -> diff f{1,2} between checkins sym1 & sym2
	 */
	if (!fsl_sym_to_rid(f, fcli_next_arg(false), FSL_SATYPE_ANY, &prid)) {
		artifact1 = fcli_next_arg(true);
		if (!fsl_rid_is_a_checkin(f, prid)) {
			if (fsl_rid_to_artifact_uuid(f, prid, FSL_SATYPE_ANY)
			    != NULL) {
				rc = RC(FSL_RC_TYPE,
				    "artifact [%s] not resolvable to a checkin",
				    artifact1);
				goto end;
			}
			++blob;
		}
		if (!fsl_sym_to_rid(f, fcli_next_arg(false), FSL_SATYPE_ANY,
		    &rid)) {
			artifact2 = fcli_next_arg(true);
			diff_type = FNC_DIFF_COMMIT;
			if (!fsl_rid_is_a_checkin(f, rid)) {
				if (fsl_rid_to_artifact_uuid(f,
				    prid, FSL_SATYPE_ANY) != NULL) {
					rc = RC(FSL_RC_TYPE, "artifact [%s] "
					    "not resolvable to a checkin",
					    artifact2);
					goto end;
				}
				++blob;
			}
		}
	}
	if (fcli_error()->code == FSL_RC_NOT_FOUND) {
		fcli_err_reset();  /* If args aren't symbols, treat as paths. */
		rc = 0;
	}
	if (blob == 2)
		diff_type = FNC_DIFF_BLOB;
	if (!artifact1 && diff_type != FNC_DIFF_BLOB) {
		artifact1 = "current";
		rc = fsl_sym_to_rid(f, artifact1, FSL_SATYPE_CHECKIN, &prid);
		if (rc || prid < 0) {
			rc = RC(rc, "%s", "fsl_sym_to_rid");
			goto end;
		}
	}
	if (!artifact2 && diff_type != FNC_DIFF_BLOB) {
		diff_type = FNC_DIFF_CKOUT;
		fsl_ckout_version_info(f, &rid, NULL);
		if ((rc = fsl_ckout_changes_scan(f)))
			return RC(rc, "%s", "fsl_ckout_changes_scan");
		if (!fsl_strcmp(artifact1, "current") &&
		    !fsl_ckout_has_changes(f)) {
			fsl_fprintf(stdout, "No local changes.\n");
			return rc;
		}
	}
	while (fcli_next_arg(false) && diff_type != FNC_DIFF_BLOB) {
		struct fnc_pathlist_entry *ins;
		char *path, *path_to_diff;
		rc = map_repo_path(&path0);
		path = path0;
		while (path[0] == '/')
			++path;
		if (rc) {
			if (rc != FSL_RC_NOT_FOUND ||
			    (!fsl_strcmp(artifact1, "current") && !artifact2))
				goto end;
			rc = 0;
			fcli_err_reset();
			/* Path may be valid in tree of specified commit(s). */
			const fsl_card_F *cf = NULL;
			rc = fsl_deck_load_sym(f, &d, artifact1,
			    FSL_SATYPE_CHECKIN);
			if (rc)
				goto end;
			cf = fsl_deck_F_search(&d, path);
			if (cf == NULL) {
				if (!artifact2) {
					rc = RC(FSL_RC_NOT_FOUND,
					    "'%s' not found in tree [%s]", path,
					    artifact1);
					goto end;
				}
				fsl_deck_finalize(&d);
				rc = fsl_deck_load_sym(f, &d, artifact2,
				    FSL_SATYPE_CHECKIN);
				if (rc)
					goto end;
				cf = fsl_deck_F_search(&d, path);
				if (cf == NULL) {
					rc = RC(FSL_RC_NOT_FOUND,
					    "'%s' not found in trees [%s] [%s]",
					    path, artifact1, artifact2);
					goto end;
				}
			}
		}
		path_to_diff = fsl_strdup(path);
		if (path_to_diff == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		rc = fnc_pathlist_insert(&ins, &paths, path_to_diff, NULL);
		if (rc || ins == NULL /* Duplicate path. */)
			fsl_free(path_to_diff);
		if (rc)
			goto end;
	}

	if (diff_type != FNC_DIFF_BLOB && diff_type != FNC_DIFF_CKOUT) {
		q = fsl_stmt_malloc();
		rc = commit_builder(&commit, rid, q);
		if (rc)
			goto end;
		if (commit->prid == prid)
			showmeta = true;
		else {
			fsl_free(commit->puuid);
			commit->prid = prid;
			commit->puuid = fsl_rid_to_uuid(f, prid);
		}
	} else {
		commit = calloc(1, sizeof(*commit));
		if (commit == NULL) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
			    "%s", "calloc");
			goto end;
		}
		commit->prid = prid;
		commit->rid = rid;
		commit->puuid = fsl_rid_to_uuid(f, prid);
		commit->uuid = fsl_rid_to_uuid(f, rid);
		commit->type = fsl_strdup("blob");
		commit->diff_type = diff_type;
	}

	rc = init_curses();
	if (rc)
		goto end;

	if (fnc_init.context) {
		if ((rc = strtonumcheck(&context, fnc_init.context, INT_MIN,
		    INT_MAX)))
			goto end;
		context = MIN(DIFF_MAX_CTXT, context);
	}

	view = view_open(0, 0, 0, 0, FNC_VIEW_DIFF);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_diff_view(view, commit, context, fnc_init.ws,
	    fnc_init.invert, !fnc_init.quiet, NULL, showmeta, &paths);
	if (!rc)
		rc = view_loop(view);
end:
	fsl_free(path0);
	fsl_deck_finalize(&d);
	fsl_stmt_finalize(q);
	if (commit)
		fnc_commit_artifact_close(commit);
	TAILQ_FOREACH(pe, &paths, entry)
		free((char *)pe->path);
	fnc_pathlist_free(&paths);
	return rc;
}

static int
browse_commit_tree(struct fnc_view **new_view, int start_col,
    struct commit_entry *entry, const char *path)
{
	struct fnc_view	*tree_view;
	int		 rc = 0;

	tree_view = view_open(0, 0, 0, start_col, FNC_VIEW_TREE);
	if (tree_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_tree_view(tree_view, path, entry->commit->rid);
	if (rc)
		return rc;

	*new_view = tree_view;

	return rc;
}

static int
cmd_tree(fcli_command const *argv)
{
	fsl_cx		*f = fcli_cx();
	struct fnc_view	*view;
	char		*path = NULL;
	fsl_id_t	 rid;
	int		 rc = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		goto end;

	rc = map_repo_path(&path);
	if (rc)
		goto end;
	if (fnc_init.sym)
		rc = fsl_sym_to_rid(f, fnc_init.sym, FSL_SATYPE_ANY, &rid);
	else
		fsl_ckout_version_info(f, &rid, NULL);

	if (rc) {
		switch (rc) {
		case FSL_RC_AMBIGUOUS:
			RC(rc, "prefix too ambiguous [%s]",
			    fnc_init.sym);
			goto end;
		case FSL_RC_NOT_A_REPO:
			RC(rc, "%s tree needs a local checkout",
			    fcli_progname());
			goto end;
		case FSL_RC_NOT_FOUND:
			RC(rc, "invalid symbolic checkin name [%s]",
			    fnc_init.sym);
			goto end;
		case FSL_RC_MISUSE:
			/* FALL THROUGH */
		default:
			goto end;
		}
	}

	/* In 'fnc tree -R repo.db [path]' case, use the latest checkin. */
	if (rid == 0) {
		rc = fsl_sym_to_rid(f, "tip", FSL_SATYPE_CHECKIN, &rid);
		if (rc)
			goto end;
	} else if (!fsl_rid_is_a_checkin(f, rid)) {
		rc = RC(FSL_RC_TYPE, "%s tree requires check-in artifact",
		    fcli_progname());
		goto end;
	}

	rc = init_curses();
	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_TREE);
	if (view == NULL) {
		RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_tree_view(view, path, rid);
	if (!rc)
		rc = view_loop(view);
end:
	fsl_free(path);
	return rc;
}

static int
open_tree_view(struct fnc_view *view, const char *path, fsl_id_t rid)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_tree_view_state	*s = &view->state.tree;
	int				 rc = 0;

	TAILQ_INIT(&s->parents);
	s->show_id = false;
	s->colour = !fnc_init.nocolour && has_colors();
	s->rid = rid;
	s->commit_id = fsl_rid_to_uuid(f, rid);
	if (s->commit_id == NULL)
		return RC(FSL_RC_AMBIGUOUS, "%s", "fsl_rid_to_uuid");

	/*
	 * Construct tree of entire repository from which all (sub)tress will
	 * be derived. This object will be released when this view closes.
	 */
	rc = create_repository_tree(&s->repo, &s->commit_id, s->rid);
	if (rc)
		goto end;

	/*
	 * Open the initial root level of the repository tree now. Subtrees
	 * opened during traversal are built and destroyed on demand.
	 */
	rc = tree_builder(s->repo, &s->root, "/");
	if (rc)
		goto end;
	s->tree = s->root;
	/*
	 * If user has supplied a path arg (i.e., fnc tree path/in/repo), or
	 * has selected a commit from an 'fnc timeline path/in/repo' command,
	 * walk the path and open corresponding (sub)tree objects now.
	 */
	if (!fnc_path_is_root_dir(path)) {
		rc = walk_tree_path(s, s->repo, &s->root, path);
		if (rc)
			goto end;
	}


	if ((s->tree_label = fsl_mprintf("checkin %s", s->commit_id)) == NULL) {
		rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		goto end;
	}

	s->first_entry_onscreen = &s->tree->entries[0];
	s->selected_entry = &s->tree->entries[0];

	if (s->colour)
		set_colours(&s->colours, FNC_VIEW_TREE);

	view->show = show_tree_view;
	view->input = tree_input_handler;
	view->close = close_tree_view;
	view->search_init = tree_search_init;
	view->search_next = tree_search_next;
end:
	if (rc)
		close_tree_view(view);
	return rc;
}

/*
 * Decompose the supplied path into its constituent components, then build,
 * open and visit each subtree segment on the way to the requested entry.
 */
static int
walk_tree_path(struct fnc_tree_view_state *s, struct fnc_repository_tree *repo,
    struct fnc_tree_object **root, const char *path)
{
	struct fnc_tree_object	*tree = NULL;
	const char		*p;
	char			*slash, *subpath = NULL;
	int			 rc = 0;

	/* Find each slash and open preceding directory segment as a tree. */
	p = path;
	while (*p) {
		struct fnc_tree_entry	*te;
		char			*te_name;

		while (p[0] == '/')
			p++;

		slash = strchr(p, '/');
		if (slash == NULL)
			te_name = fsl_strdup(p);
		else
			te_name = fsl_strndup(p, slash - p);
		if (te_name == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			break;
		}

		te = find_tree_entry(s->tree, te_name, fsl_strlen(te_name));
		if (te == NULL) {
			rc = RC(FSL_RC_NOT_FOUND, "find_tree_entry(%s)",
			    te_name);
			fsl_free(te_name);
			break;
		}
		fsl_free(te_name);

		s->first_entry_onscreen = s->selected_entry = te;
		if (!S_ISDIR(s->selected_entry->mode))
			break;	/* If a file, jump to this entry. */

		slash = strchr(p, '/');
		if (slash)
			subpath = fsl_strndup(path, slash - path);
		else
			subpath = fsl_strdup(path);
		if (subpath == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			break;
		}

		rc = tree_builder(repo, &tree, subpath + 1 /* Leading slash */);
		if (rc)
			break;
		rc = visit_subtree(s, tree);
		if (rc) {
			fnc_object_tree_close(tree);
			break;
		}

		if (slash == NULL)
			break;
		fsl_free(subpath);
		subpath = NULL;
		p = slash;
	}

	fsl_free(subpath);
	return rc;
}

/*
 * This routine constructs the repository tree, repo, which is a DLL; from this
 * tree, all displayed (sub)trees are derived. File paths are extracted from F
 * cards of the checkin identified by id referenced in the repo database by rid.
 */
static int
create_repository_tree(struct fnc_repository_tree **repo, fsl_uuid_str *id,
    fsl_id_t rid)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_repository_tree	*ptr;
	fsl_deck			 d = fsl_deck_empty;
	const fsl_card_F		*cf = NULL;
	int				 rc = 0;

	ptr = fsl_malloc(sizeof(struct fnc_repository_tree));
	if (ptr == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	memset(ptr, 0, sizeof(struct fnc_repository_tree));

	rc = fsl_deck_load_rid(fcli_cx(), &d, rid, FSL_SATYPE_CHECKIN);
	if (rc)
		return RC(rc, "fsl_deck_load_rid(%d) [%s]", rid, id);
	rc = fsl_deck_F_rewind(&d);
	if (rc)
		goto end;;
	rc = fsl_deck_F_next(&d, &cf);
	if (rc)
		goto end;;

	while (cf) {
		char		*filename = NULL, *uuid = NULL;
		fsl_time_t	 mtime;

		filename = fsl_strdup(cf->name);
		if (filename == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		uuid = fsl_strdup(cf->uuid);
		if (uuid == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		rc = fsl_mtime_of_F_card(f, rid, cf, &mtime);
		if (!rc)
			rc = link_tree_node(ptr, filename, uuid, mtime);
		fsl_free(filename);
		fsl_free(uuid);
		if (!rc)
			rc = fsl_deck_F_next(&d, &cf);
		if (rc)
			goto end;
	}
end:
	fsl_deck_finalize(&d);

	*repo = ptr;
	return rc;
}

/*
 * This routine constructs the (sub)trees that are displayed. The directory dir
 * and its contents form a subtree, which is an array of tree entries copied
 * from DLL nodes in repo and stored in tree. This routine is called for each
 * directory that is displayed as a tree.
 */
static int
tree_builder(struct fnc_repository_tree *repo, struct fnc_tree_object **tree,
    const char *dir)
{
	struct fnc_tree_entry		*te = NULL;
	struct fnc_repo_tree_node	*tn = NULL;
	int				 i = 0;

	*tree = NULL;
	*tree = fsl_malloc(sizeof(**tree));
	if (*tree == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	memset(*tree, 0, sizeof(**tree));

	/* Count how many elements will comprise the tree to be allocated. */
	for(tn = repo->head; tn; tn = tn->next) {
		if ((!tn->parent_dir && fsl_strcmp(dir, "/")) ||
		    (tn->parent_dir && fsl_strcmp(dir, tn->parent_dir->path)))
			continue;
		++i;
	}
	(*tree)->entries = calloc(i, sizeof(struct fnc_tree_entry));
	if ((*tree)->entries == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
	/* Construct the tree to be displayed. */
	for(tn = repo->head, i = 0; tn; tn = tn->next) {
		if ((!tn->parent_dir && fsl_strcmp(dir, "/")) ||
		    (tn->parent_dir && fsl_strcmp(dir, tn->parent_dir->path)))
			continue;
		te = &(*tree)->entries[i];
		te->mode = tn->mode;
		te->mtime = tn->mtime;
		te->basename = fsl_strdup(tn->basename);
		if (te->basename == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->path = fsl_strdup(tn->path);
		if (te->path == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->uuid = fsl_strdup(tn->uuid);
		if (te->uuid == NULL && !S_ISDIR(te->mode))
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->idx = i++;
	}
	(*tree)->nentries = i;

	return 0;
}

#if 0
static void
delete_tree_node(struct fnc_tree_entry **head, struct fnc_tree_entry *del)
{
	struct fnc_tree_entry *temp = *head, *prev;

	if (temp == del) {
		*head = temp->next;
		fsl_free(temp);
		return;
	}

	while (temp != NULL && temp != del) {
		prev = temp;
		temp = temp->next;
	}

	if (temp == NULL)
		return;

	prev->next = temp->next;

	fsl_free(temp);
}
#endif

/*
 * This routine inserts nodes into the doubly-linked repository tree. Each
 * path component of path (i.e., tokens delimited by '/') becomes a node in
 * tree. The final path component of each segment is the node's .basename, and
 * its full repository relative path its .path. All files in a given directory
 * will comprise the directory node's .children list, and each file node's
 * .sibling list; said directory will be each file node's .parent_dir. The
 * elements of each requested tree will be identified by the node's .parent_dir;
 * that is, each node with the same parent_dir will be an entry in the same tree
 *   tree    The repository tree into which nodes are inserted
 *   path    The repository relative pathname of the versioned file
 *   uuid    The SHA hash of the file
 *   mtime   Modification time of the file
 * Returns 0 on success, non-zero on error.
 */
static int
link_tree_node(struct fnc_repository_tree *tree, const char *path,
    const char *uuid, fsl_time_t mtime)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_repo_tree_node	*parent_dir;
	fsl_buffer			 buf = fsl_buffer_empty;
	struct stat			 s;
	int				 i, rc = 0;

	parent_dir = tree->tail;
	while (parent_dir != 0 &&
	    (strncmp(parent_dir->path, path, parent_dir->pathlen) != 0 ||
            path[parent_dir->pathlen] != '/'))
		parent_dir = parent_dir->parent_dir;

	i = parent_dir ? parent_dir->pathlen + 1 : 0;

	while (path[i]) {
		struct fnc_repo_tree_node	*tn;
		int				 nodesz, slash = i;

		/* Find slash to demarcate each path component. */
		while (path[i] && path[i] != '/')
			i++;
		nodesz = sizeof(*tn) + i + 1;

		/*
		 * If not at end of path string, node is a directory so don't
		 * allocate space for the hash.
		 */
		if (uuid != 0 && path[i] == '\0')
			nodesz += FSL_STRLEN_K256 + 1; /* NUL */
		tn = fsl_malloc(nodesz);
		if (tn == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
		memset(tn, 0, sizeof(*tn));

		tn->path = (char *)&tn[1];
		memcpy(tn->path, path, i);
		tn->path[i] = '\0';
		tn->pathlen = i;

		if (uuid != 0 && path[i] == '\0') {
			tn->uuid = tn->path + i + 1;
			memcpy(tn->uuid, uuid, fsl_strlen(uuid) + 1);
		}

		tn->basename = tn->path + slash;

		/* Insert node into DLL or make it the head if first. */
		if (tree->tail) {
			tree->tail->next = tn;
			tn->prev = tree->tail;
		} else
			tree->head = tn;

		tree->tail = tn;
		tn->parent_dir = parent_dir;
		if (parent_dir) {
			if (parent_dir->children)
				parent_dir->lastchild->sibling = tn;
			else
				parent_dir->children = tn;
			tn->nparents = parent_dir->nparents + 1;
			parent_dir->lastchild = tn;
		} else {
			if (tree->rootail)
				tree->rootail->sibling = tn;
			tree->rootail = tn;
		}

		tn->mtime = mtime;
		while (path[i] == '/')	/* Consume slashes. */
			++i;
		parent_dir = tn;

		/* Stat path for tree display features. */
		rc = fsl_file_canonical_name2(f->ckout.dir, tn->path, &buf,
		    false);
		if (rc)
			goto end;
		if (lstat(fsl_buffer_cstr(&buf), &s) == -1) {
			if (errno == ENOENT)
				tn->mode = (!fsl_strcmp(tn->path, path) &&
				    tn->uuid) ? S_IFREG : S_IFDIR;
			else {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
				    "lstat(%s)", fsl_buffer_cstr(&buf));
				goto end;
			}
		} else
			tn->mode = s.st_mode;
		fsl_buffer_reuse(&buf);
	}

	while (parent_dir && parent_dir->parent_dir) {
		if (parent_dir->parent_dir->mtime < parent_dir->mtime)
			parent_dir->parent_dir->mtime = parent_dir->mtime;
		parent_dir = parent_dir->parent_dir;
	}
end:
	fsl_buffer_clear(&buf);
	return rc;
}

static int
show_tree_view(struct fnc_view *view)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	char				*treepath;
	int				 rc = 0;

	rc = tree_entry_path(&treepath, &s->parents, NULL);
	if (rc)
		return rc;

	rc = draw_tree(view, treepath);
	fsl_free(treepath);
	draw_vborder(view);

	return rc;
}

/*
 * Construct absolute repository path of the currently selected tree entry to
 * display in the tree view header, or pass to open_timeline_view() to construct
 * a timeline of all commits modifying path.
 */
static int
tree_entry_path(char **path, struct fnc_parent_trees *parents,
    struct fnc_tree_entry *te)
{
	struct fnc_parent_tree	*pt;
	size_t			 len = 2;  /* Leading slash and NUL. */
	int			 rc = 0;

	TAILQ_FOREACH(pt, parents, entry)
		len += strlen(pt->selected_entry->basename) + 1 /* slash */;
	if (te)
		len += strlen(te->basename);

	*path = calloc(1, len);
	if (path == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	(*path)[0] = '/';  /* Make it absolute from the repository root. */
	pt = TAILQ_LAST(parents, fnc_parent_trees);
	while (pt) {
		const char *name = pt->selected_entry->basename;
		if (strlcat(*path, name, len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, %s, %d)",
			    *path, name, len);
			goto end;
		}
		if (strlcat(*path, "/", len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, \"/\", %d)",
			    *path, len);
			goto end;
		}
		pt = TAILQ_PREV(pt, fnc_parent_trees, entry);
	}
	if (te) {
		if (strlcat(*path, te->basename, len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, %s, %d)",
			    *path, te->basename, len);
			goto end;
		}
	}
end:
	if (rc) {
		fsl_free(*path);
		*path = NULL;
	}
	return rc;
}

/*
 * Draw the currently visited tree. Headline view with the checkin's SHA hash,
 * and write subheader comprised of the tree path. Lexicographically order nodes
 * (cf. ls(1)) and postfix with identifier corresponding to the file mode as
 * returned by lstat(2) such that the tree takes the following form:
 *
 *  checkin COMMIT-HASH
 *  /absolute/repository/tree/path/
 *
 *   ..
 *   dir/
 *   executable*
 *   regularfile
 *   symlink@ -> /path/to/source/file
 *
 * If the 'i' key binding is entered, prefix each versioned file with its
 * SHA{1,3} hash. Directories, however, have no such hash UUID to display.
 */
static int
draw_tree(struct fnc_view *view, const char *treepath)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fnc_tree_entry		*te;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	int				 match = -1, rc = 0;
	int				 wstrlen, n, idx, nentries;
	int				 limit = view->nlines;
	uint_fast8_t			 hashlen = FSL_UUID_STRLEN_MIN;

	s->ndisplayed = 0;
	werase(view->window);
	if (limit == 0)
		return rc;

	/* Write (highlighted) headline (if view is active in splitscreen). */
	rc = formatln(&wcstr, &wstrlen, s->tree_label, view->ncols, 0);
	if (rc)
		return rc;
	if (screen_is_shared(view))
		wstandout(view->window);
	if (s->colour)
		c = get_colour(&s->colours, FNC_COMMIT_ID);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, wcstr);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	if (screen_is_shared(view))
		wstandend(view->window);
	fsl_free(wcstr);
	wcstr = NULL;
	if (wstrlen < view->ncols - 1)
		waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;

	/* Write this (sub)tree's absolute repository path subheader. */
	rc = formatln(&wcstr, &wstrlen, treepath, view->ncols, 0);
	if (rc)
		return rc;
	waddwstr(view->window, wcstr);
	fsl_free(wcstr);
	wcstr = NULL;
	if (wstrlen < view->ncols - 1)
		waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;
	waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;

	/* Write parent dir entry (i.e., "..") if top of the tree is in view. */
	if (s->first_entry_onscreen == NULL) {
		te = &s->tree->entries[0];
		if (s->selected_idx == 0) {
			if (view->active)
				wattr_on(view->window, A_REVERSE, NULL);
			s->selected_entry = NULL;
		}
		waddstr(view->window, "  ..\n");
		if (s->selected_idx == 0 && view->active)
			wattr_off(view->window, A_REVERSE, NULL);
		++s->ndisplayed;
		if (--limit <= 0)
			return rc;
		n = 1;
	} else {
		n = 0;
		te = s->first_entry_onscreen;
	}

	nentries = s->tree->nentries;
	for (idx = 0; idx < nentries; ++idx)	/* Find max hash length. */
		if (hashlen < fsl_strlen(s->tree->entries[idx].uuid))
			hashlen = fsl_strlen(s->tree->entries[idx].uuid);
	/* Iterate and write tree nodes postfixed with path type identifier. */
	for (idx = te->idx; idx < nentries; ++idx) {
		char		*line = NULL, *idstr = NULL, *targetlnk = NULL;
		const char	*modestr = "";
		mode_t		 mode;

		if (idx < 0 || idx >= s->tree->nentries)
			return 0;
		te = &s->tree->entries[idx];
		mode = te->mode;

		if (s->show_id) {
			idstr = fsl_strdup(te->uuid);
			/* Directories don't have UUIDs; pad with "..." dots. */
			if (idstr == NULL && !S_ISDIR(mode))
				return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			/* If needed, pad SHA1 hash to align w/ SHA3 hashes. */
			if (idstr == NULL || fsl_strlen(idstr) < hashlen) {
				char buf[hashlen], pad = '.';
				idstr = fsl_mprintf("%s%s", idstr ? idstr : "",
				    (char *)memset(buf, pad,
				    hashlen - fsl_strlen(idstr)));
				if (idstr == NULL)
					return RC(FSL_RC_RANGE,
					    "%s", "fsl_mprintf");
				idstr[hashlen] = '\0';
				/* idstr = fsl_mprintf("%*c", hashlen, ' '); */
			}
		}
		if (S_ISLNK(mode)) {
			fsl_size_t	ch;

			rc = tree_entry_get_symlink_target(&targetlnk, te);
			if (rc) {
				fsl_free(idstr);
				return rc;
			}
			for (ch = 0; ch < fsl_strlen(targetlnk); ++ch) {
				if (!isprint((unsigned char)targetlnk[ch]))
					targetlnk[ch] = '?';
			}
			modestr = "@";
		}
		else if (S_ISDIR(mode))
			modestr = "/";
		else if (mode & S_IXUSR)
			modestr = "*";
		if ((line = fsl_mprintf("%s  %s%s%s%s", idstr ? idstr : "",
		    te->basename, modestr, targetlnk ? " -> ": "",
		    targetlnk ? targetlnk : "")) == NULL) {
			fsl_free(idstr);
			fsl_free(targetlnk);
			return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		}
		fsl_free(idstr);
		fsl_free(targetlnk);
		rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0);
		if (rc) {
			fsl_free(line);
			break;
		}
		if (n == s->selected_idx) {
			if (view->active)
				wattr_on(view->window, A_REVERSE, NULL);
			s->selected_entry = te;
		}
		if (s->colour && (match = fsl_list_index_of(&s->colours, line,
		    match_line)) != -1)
			c = s->colours.list[match];
		else
			c = NULL;
		if (c)
			wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
		waddwstr(view->window, wcstr);
		if (c)
			wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
		if (wstrlen < view->ncols - 1)
			waddch(view->window, '\n');
		if (n == s->selected_idx && view->active)
			wattr_off(view->window, A_REVERSE, NULL);
		fsl_free(line);
		fsl_free(wcstr);
		wcstr = NULL;
		++n;
		++s->ndisplayed;
		s->last_entry_onscreen = te;
		if (--limit <= 0)
			break;
	}

	return rc;
}

static int
tree_entry_get_symlink_target(char **targetlnk, struct fnc_tree_entry *te)
{
	struct stat	 s;
	fsl_buffer	 fb = fsl_buffer_empty;
	char		*buf = NULL;
	ssize_t		 nbytes, bufsz;
	int		 rc = 0;

	*targetlnk = NULL;

	fsl_file_canonical_name2(fcli_cx()->ckout.dir, te->path, &fb, false);
	if (lstat(fsl_buffer_cstr(&fb), &s) == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), "lstat(%s)",
		    fsl_buffer_cstr(&fb));
		goto end;
	}

	bufsz = s.st_size ? (s.st_size + 1 /* NUL */) : PATH_MAX;
	buf = fsl_malloc(bufsz);
	if (buf == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_malloc");
		goto end;
	}

	nbytes = readlink(fsl_buffer_cstr(&fb), buf, bufsz);
	if (nbytes == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "readlink(%s)",
		    fsl_buffer_cstr(&fb));
		goto end;
	}
	buf[nbytes] = '\0';	/* readlink() does _not_ NUL terminate */
end:
	fsl_buffer_clear(&fb);
	if (rc)
		fsl_free(buf);
	*targetlnk = buf;
	return rc;
	/*
	 * XXX Not sure if we should rely on fossil(1) populating symlinks
	 * with the path of the target source file to obtain the target link.
	 */
	/* fsl_cx		*f = fcli_cx(); */
	/* fsl_buffer	 blob = fsl_buffer_empty; */
	/* fsl_id_t	 rid; */

	/* if (!((te->mode & (S_IFDIR | S_IFLNK)) == S_IFLNK)) */
	/* 	return RC(FSL_RC_TYPE, "file not symlink [%s]", te->path); */
	/* rc = fsl_sym_to_rid(f, te->uuid, FSL_SATYPE_ANY, &rid); */
	/* if (!rc) */
	/* 	rc = fsl_content_blob(f, rid, &blob); */
	/* if (rc) */
	/* 	return rc; */

	/* *targetlnk = fsl_strdup(fsl_buffer_str(&blob)); */
	/* fsl_buffer_clear(&blob); */
}

static int
tree_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_view			*timeline_view/*, *branch_view */;
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fnc_tree_entry		*te;
	int				 n, start_col = 0, rc = 0;

	switch (ch) {
	case 'c':
		s->colour = !s->colour;
		break;
	case 'i':
		s->show_id = !s->show_id;
		break;
	case 't':
		if (!s->selected_entry)
			break;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		rc = timeline_tree_entry(&timeline_view, start_col, s);
		view->active = false;
		timeline_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				return rc;
			view_set_child(view, timeline_view);
			view->focus_child = true;
		} else
			*new_view = timeline_view;
		break;
	case 'g':
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	case KEY_HOME:
		s->selected_idx = 0;
		if (s->tree == s->root)
			s->first_entry_onscreen = &s->tree->entries[0];
		else
			s->first_entry_onscreen = NULL;
		break;
	case KEY_END:
	case 'G':
		s->selected_idx = 0;
		te = &s->tree->entries[s->tree->nentries - 1];
		for (n = 0; n < view->nlines - 3; ++n) {
			if (te == NULL) {
				if(s->tree != s->root) {
					s->first_entry_onscreen = NULL;
					++n;
				}
				break;
			}
			s->first_entry_onscreen = te;
			te = get_tree_entry(s->tree, te->idx - 1);
		}
		if (n > 0)
			s->selected_idx = n - 1;
		break;
	case KEY_UP:
	case 'k':
		if (s->selected_idx > 0) {
			--s->selected_idx;
			break;
		}
		tree_scroll_up(s, 1);
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->tree == s->root) {
			if (&s->tree->entries[0] == s->first_entry_onscreen)
				s->selected_idx = 0;
		} else {
			if (s->first_entry_onscreen == NULL)
				s->selected_idx = 0;
		}
		tree_scroll_up(s, MAX(0, view->nlines - 3));
		break;
	case KEY_DOWN:
	case 'j':
		if (s->selected_idx < s->ndisplayed - 1) {
			++s->selected_idx;
			break;
		}
		if (get_tree_entry(s->tree, s->last_entry_onscreen->idx + 1)
		    == NULL)
			break;	/* Reached last entry. */
		tree_scroll_down(s, 1);
		break;
	case KEY_NPAGE:
	case CTRL('f'):
		if (get_tree_entry(s->tree, s->last_entry_onscreen->idx + 1)
		    == NULL) {
			/*
			 * When the last entry on screen is the last node in the
			 * tree move cursor to it instead of scrolling the view.
			 */
			if (s->selected_idx < s->ndisplayed - 1)
				s->selected_idx = s->ndisplayed - 1;
			break;
		}
		tree_scroll_down(s, view->nlines - 3);
		break;
	case KEY_BACKSPACE:
	case KEY_ENTER:
	case KEY_LEFT:
	case KEY_RIGHT:
	case '\r':
	case 'h':
	case 'l':
		/*
		 * h/backspace/arrow-left: return to parent dir irrespective
		 * of selected entry type (unless already at root).
		 * l/arrow-right: move into selected dir entry.
		 */
		if (ch != KEY_RIGHT && ch != 'l' && (s->selected_entry == NULL
		    || ch == 'h' || ch == KEY_BACKSPACE || ch == KEY_LEFT)) {
			struct fnc_parent_tree	*parent;
			/* h/backspace/left-arrow pressed or ".." selected. */
			if (s->tree == s->root)
				break;
			parent = TAILQ_FIRST(&s->parents);
			TAILQ_REMOVE(&s->parents, parent,
			    entry);
			fnc_object_tree_close(s->tree);
			s->tree = parent->tree;
			s->first_entry_onscreen = parent->first_entry_onscreen;
			s->selected_entry = parent->selected_entry;
			s->selected_idx = parent->selected_idx;
			fsl_free(parent);
		} else if (s->selected_entry != NULL &&
		    S_ISDIR(s->selected_entry->mode)) {
			struct fnc_tree_object	*subtree = NULL;
			rc = tree_builder(s->repo, &subtree,
			    s->selected_entry->path);
			if (rc)
				break;
			rc = visit_subtree(s, subtree);
			if (rc) {
				fnc_object_tree_close(subtree);
				break;
			}
		} else if (S_ISREG(s->selected_entry->mode)) {
			struct fnc_view *blame_view;
			int start_col = view_is_parent(view) ?
			    view_split_start_col(view->start_col) : 0;

			rc = blame_tree_entry(&blame_view, start_col,
			    s->selected_entry, &s->parents, s->commit_id);
			if (rc)
				break;
			view->active = false;
			blame_view->active = true;
			if (view_is_parent(view)) {
				rc = view_close_child(view);
				if (rc)
					return rc;
				view_set_child(view, blame_view);
				view->focus_child = true;
			} else
				*new_view = blame_view;
		}
		break;
	case KEY_RESIZE:
		if (view->nlines >= 4 && s->selected_idx >= view->nlines - 3)
			s->selected_idx = view->nlines - 4;
		break;
	default:
		break;
	}

	return rc;
}

static int
timeline_tree_entry(struct fnc_view **new_view, int start_col,
    struct fnc_tree_view_state *s)
{
	struct fnc_view	*timeline_view;
	char		*path;
	int		 rc = 0;

	*new_view = NULL;

	timeline_view = view_open(0, 0, 0, start_col, FNC_VIEW_TIMELINE);
	if (timeline_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	/* Construct repository relative path for timeline query. */
	rc = tree_entry_path(&path, &s->parents, s->selected_entry);
	if (rc)
		return rc;

	rc = open_timeline_view(timeline_view, s->rid, path);
	if (rc)
		view_close(timeline_view);
	else
		*new_view = timeline_view;

	fsl_free(path);
	return rc;
}

static void
tree_scroll_up(struct fnc_tree_view_state *s, int maxscroll)
{
	struct fnc_tree_entry	*te;
	int			 isroot, i = 0;

	isroot = s->tree == s->root;

	if (s->first_entry_onscreen == NULL)
		return;

	te = get_tree_entry(s->tree, s->first_entry_onscreen->idx - 1);
	while (i++ < maxscroll) {
		if (te == NULL) {
			if (!isroot)
				s->first_entry_onscreen = NULL;
			break;
		}
		s->first_entry_onscreen = te;
		te = get_tree_entry(s->tree, te->idx - 1);
	}
}

static void
tree_scroll_down(struct fnc_tree_view_state *s, int maxscroll)
{
	struct fnc_tree_entry	*next, *last;
	int			 n = 0;

	if (s->first_entry_onscreen)
		next = get_tree_entry(s->tree,
		    s->first_entry_onscreen->idx + 1);
	else
		next = &s->tree->entries[0];

	last = s->last_entry_onscreen;
	while (next && last && n++ < maxscroll) {
		last = get_tree_entry(s->tree, last->idx + 1);
		if (last) {
			s->first_entry_onscreen = next;
			next = get_tree_entry(s->tree, next->idx + 1);
		}
	}
}

static int
visit_subtree(struct fnc_tree_view_state *s, struct fnc_tree_object *subtree)
{
	struct fnc_parent_tree	*parent;

	parent = calloc(1, sizeof(*parent));
	if (parent == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	parent->tree = s->tree;
	parent->first_entry_onscreen = s->first_entry_onscreen;
	parent->selected_entry = s->selected_entry;
	parent->selected_idx = s->selected_idx;
	TAILQ_INSERT_HEAD(&s->parents, parent, entry);
	s->tree = subtree;
	s->selected_idx = 0;
	s->first_entry_onscreen = NULL;

	return 0;
}

static int
blame_tree_entry(struct fnc_view **new_view, int start_col,
    struct fnc_tree_entry *te, struct fnc_parent_trees *parents,
    fsl_uuid_str commit_id)
{
	struct fnc_view	*blame_view;
	char		*path;
	int		 rc = 0;

	*new_view = NULL;

	rc = tree_entry_path(&path, parents, te);
	if (rc)
		return rc;

	blame_view = view_open(0, 0, 0, start_col, FNC_VIEW_BLAME);
	if (blame_view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_blame_view(blame_view, path, commit_id, 0, 0);
	if (rc)
		view_close(blame_view);
	else
		*new_view = blame_view;
end:
	fsl_free(path);
	return rc;
}

static int
tree_search_init(struct fnc_view *view)
{
	struct fnc_tree_view_state *s = &view->state.tree;

	s->matched_entry = NULL;
	return 0;
}

static int
tree_search_next(struct fnc_view *view)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fnc_tree_entry		*te = NULL;
	int				 rc = 0;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
		return rc;
	}

	if (s->matched_entry) {
		if (view->searching == SEARCH_FORWARD) {
			if (s->selected_entry)
				te = &s->tree->entries[s->selected_entry->idx
				    + 1];
			else
				te = &s->tree->entries[0];
		} else {
			if (s->selected_entry == NULL)
				te = &s->tree->entries[s->tree->nentries - 1];
			else
				te = &s->tree->entries[s->selected_entry->idx
				    - 1];
		}
	} else {
		if (view->searching == SEARCH_FORWARD)
			te = &s->tree->entries[0];
		else
			te = &s->tree->entries[s->tree->nentries - 1];
	}

	while (1) {
		if (te == NULL) {
			if (s->matched_entry == NULL) {
				view->search_status = SEARCH_CONTINUE;
				return rc;
			}
			if (view->searching == SEARCH_FORWARD)
				te = &s->tree->entries[0];
			else
				te = &s->tree->entries[s->tree->nentries - 1];
		}

		if (match_tree_entry(te, &view->regex)) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_entry = te;
			break;
		}

		if (view->searching == SEARCH_FORWARD)
			te = &s->tree->entries[te->idx + 1];
		else
			te = &s->tree->entries[te->idx - 1];
	}

	if (s->matched_entry) {
		s->first_entry_onscreen = s->matched_entry;
		s->selected_idx = 0;
	}

	return rc;
}

static int
match_tree_entry(struct fnc_tree_entry *te, regex_t *regex)
{
	regmatch_t regmatch;

	return regexec(regex, te->basename, 1, &regmatch, 0) == 0;
}

struct fnc_tree_entry *
get_tree_entry(struct fnc_tree_object *tree, int i)
{
	if (i < 0 || i >= tree->nentries)
		return NULL;

	return &tree->entries[i];
}

/* Find entry in tree with basename name. */
static struct fnc_tree_entry *
find_tree_entry(struct fnc_tree_object *tree, const char *name, size_t len)
{
	int	idx;

	/* Entries are sorted in strcmp() order. */
	for (idx = 0; idx < tree->nentries; ++idx) {
		struct fnc_tree_entry *te = &tree->entries[idx];
		int cmp = strncmp(te->basename, name, len);
		if (cmp < 0)
			continue;
		if (cmp > 0)
			break;
		if (te->basename[len] == '\0')
			return te;
	}
	return NULL;
}

static int
close_tree_view(struct fnc_view *view)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fsl_list_state		 st = { FNC_COLOUR_OBJ };

	fsl_list_clear(&s->colours, fsl_list_object_free, &st);

	fsl_free(s->tree_label);
	s->tree_label = NULL;
	fsl_free(s->commit_id);
	s->commit_id = NULL;

	while (!TAILQ_EMPTY(&s->parents)) {
		struct fnc_parent_tree *parent;
		parent = TAILQ_FIRST(&s->parents);
		TAILQ_REMOVE(&s->parents, parent, entry);
		if (parent->tree != s->root)
			fnc_object_tree_close(parent->tree);
		fsl_free(parent);

	}

	if (s->tree != NULL && s->tree != s->root)
		fnc_object_tree_close(s->tree);
	if (s->root)
		fnc_object_tree_close(s->root);
	if (s->repo)
		fnc_close_repository_tree(s->repo);

	return 0;
}

static void
fnc_object_tree_close(struct fnc_tree_object *tree)
{
	int	idx;

	for (idx = 0; idx < tree->nentries; ++idx) {
		fsl_free(tree->entries[idx].basename);
		fsl_free(tree->entries[idx].path);
		fsl_free(tree->entries[idx].uuid);
	}

	fsl_free(tree->entries);
	fsl_free(tree);
}

static void
fnc_close_repository_tree(struct fnc_repository_tree *repo)
{
	struct fnc_repo_tree_node *next, *tn;

	tn = repo->head;
	while (tn) {
		next = tn->next;
		fsl_free(tn);
		tn = next;
	}
	fsl_free(repo);
}

static int
view_close_child(struct fnc_view *view)
{
	int	rc = 0;

	if (view->child == NULL)
		return rc;

	rc = view_close(view->child);
	view->child = NULL;

	return rc;
}

static void
view_set_child(struct fnc_view *view, struct fnc_view *child)
{
	view->child = child;
	child->parent = view;
}

static int
set_colours(fsl_list *s, enum fnc_view_id vid)
{
	struct fnc_colour	 *colour;
	const char		**regexp = NULL;
	const char		 *regexp_blame[] = {"^"};
	const char		 *regexp_timeline[] = {"^$", "^$", "^$"};
	const char		 *regexp_tree[] = {"@$", "/$", "\\*$", "^$"};
	const char		 *regexp_diff[] = {
				    "^((checkin|wiki|ticket|technote) "
				    "[0-9a-f]|hash [+-] |\\[[+~>-]] |"
				    "[+-]{3} )", "^user:", "^date:", "^tags:",
				    "^-", "^\\+", "^@@"
				  };
	int			  pairs_diff[][2] = {
				    {FNC_DIFF_META, COLOR_GREEN},
				    {FNC_USER_STR, COLOR_CYAN},
				    {FNC_DATE_STR, COLOR_YELLOW},
				    {FNC_TAGS_STR, COLOR_MAGENTA},
				    {FNC_DIFF_MINUS, COLOR_MAGENTA},
				    {FNC_DIFF_PLUS, COLOR_CYAN},
				    {FNC_DIFF_CHNK, COLOR_YELLOW}
				  };
	int			  pairs_tree[][2] = {
				    {FNC_TREE_LINK, COLOR_MAGENTA},
				    {FNC_TREE_DIR, COLOR_CYAN},
				    {FNC_TREE_EXEC, COLOR_GREEN},
				    {FNC_COMMIT_ID, COLOR_GREEN}
				  };
	int			  pairs_timeline[][2] = {
				    {FNC_COMMIT_ID, COLOR_GREEN},
				    {FNC_USER_STR, COLOR_CYAN},
				    {FNC_DATE_STR, COLOR_YELLOW}
				  };
	int			  pairs_blame[][2] = {
				    {FNC_COMMIT_ID, COLOR_GREEN}
				  };
	int			(*pairs)[2], rc = 0;
	fsl_size_t		  idx, n;

	switch (vid) {
	case FNC_VIEW_DIFF:
		n = nitems(regexp_diff);
		regexp = regexp_diff;
		pairs = pairs_diff;
		break;
	case FNC_VIEW_TREE:
		n = nitems(regexp_tree);
		regexp = regexp_tree;
		pairs = pairs_tree;
		break;
	case FNC_VIEW_TIMELINE:
		n = nitems(regexp_timeline);
		regexp = regexp_timeline;
		pairs = pairs_timeline;
		break;
	case FNC_VIEW_BLAME:
		n = nitems(regexp_blame);
		regexp = regexp_blame;
		pairs = pairs_blame;
		break;
	default:
		return RC(FSL_RC_TYPE, "%s", "invalid fnc_view_id");
	}

	for (idx = 0; idx < n; ++idx) {
		colour = fsl_malloc(sizeof(*colour));
		if (colour == NULL)
			return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
			    "%s", "fsl_malloc");

		rc = regcomp(&colour->regex, regexp[idx],
		    REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
		if (rc) {
			static char regerr[512];
			regerror(rc, &colour->regex, regerr, sizeof(regerr));
			fsl_free(colour);
			return RC(FSL_RC_ERROR, "regcomp(%s) -> %s",
			    regexp[idx], regerr);
		}

		colour->scheme = pairs[idx][0];
		init_pair(colour->scheme, pairs[idx][1], -1);
		fsl_list_append(s, colour);
	}

	return rc;
}

struct fnc_colour *
get_colour(fsl_list *colours, int scheme)
{
	struct fnc_colour	cs;
	int			match = -1;

	cs.scheme = scheme;
	match = fsl_list_index_of(colours, &cs, match_colour);

	if (match != -1)
		return colours->list[match];

	return NULL;
}

static int
match_colour(const void *target, const void *key)
{
	struct fnc_colour *c = (struct fnc_colour *)key;
	struct fnc_colour *t = (struct fnc_colour *)target;

	return (c->scheme == t->scheme) ? 0 : 1;
}

/*
 * Emulate vim(1) gg: User has 1 sec to follow first 'g' keypress with another.
 */
static bool
fnc_home(struct fnc_view *view)
{
	bool	home = true;

	halfdelay(10);	/* Block for 1 second, then return ERR. */
	if (wgetch(view->window) != 'g')
		home = false;
	cbreak();	/* Return to blocking mode on user input. */

	return home;
}

static int
cmd_blame(fcli_command const *argv)
{
	fsl_cx		*f = fcli_cx();
	struct fnc_view	*view;
	char		*path = NULL;
	fsl_uuid_str	 commit_id = NULL;
	fsl_id_t	 tip = 0, rid = 0;
	int		 nlimit = 0, rc = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		goto end;
	if (!fcli_next_arg(false)) {
		rc = RC(FSL_RC_MISSING_INFO,
		    "%s blame requires versioned file path", fcli_progname());
		goto end;
	}

	if (fnc_init.nrecords.zlimit) {
		char *n = (char *)fnc_init.nrecords.zlimit;
		bool timed;
		if (n[fsl_strlen(n) - 1] == 's') {
			n[fsl_strlen(n) - 1] = '\0';
			timed = true;
		}
		if ((rc = strtonumcheck(&nlimit, n, INT_MIN, INT_MAX)))
			goto end;
		if (timed)
			nlimit *= -1;
	}

	if (fnc_init.sym || fnc_init.reverse) {
		if (fnc_init.reverse) {
			if (!fnc_init.sym) {
				rc = RC(FSL_RC_MISSING_INFO,
				    "%s blame --reverse requires --commit",
				    fcli_progname());
				goto end;
			}
			rc = fsl_sym_to_rid(f, "tip", FSL_SATYPE_CHECKIN, &tip);
			if (rc)
				goto end;
		}
		rc = fsl_sym_to_rid(f, fnc_init.sym, FSL_SATYPE_CHECKIN, &rid);
		if (rc)
			goto end;
	} else if (!fnc_init.sym)
		fsl_ckout_version_info(f, &rid, NULL);

	rc = map_repo_path(&path);
	if (rc) {
		if (rc != FSL_RC_NOT_FOUND || !fnc_init.sym)
			goto end;
		/* Path may be valid in repository tree of specified commit. */
		rc = 0;
		fcli_err_reset();
	}

	commit_id = fsl_rid_to_uuid(f, rid);
	if (rc || (path[0] == '/' && path[1] == '\0')) {
		rc = rc ? rc : RC(FSL_RC_MISSING_INFO,
		    "%s blame requires versioned file path", fcli_progname());
		goto end;
	}

	init_curses();

	view = view_open(0, 0, 0, 0, FNC_VIEW_BLAME);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", view_open);
		goto end;
	}

	rc = open_blame_view(view, path, commit_id, tip, nlimit);
	if (rc)
		goto end;
	rc = view_loop(view);
end:
	fsl_free(path);
	fsl_free(commit_id);
	return rc;
}

static int
open_blame_view(struct fnc_view *view, char *path, fsl_uuid_str commit_id,
    fsl_id_t tip, int nlimit)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 rc = 0;

	CONCAT(STAILQ, _INIT)(&s->blamed_commits);

	s->path = fsl_strdup(path);
	if (s->path == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");

	rc = fnc_commit_qid_alloc(&s->blamed_commit, commit_id);
	if (rc) {
		fsl_free(s->path);
		return rc;
	}

	CONCAT(STAILQ, _INSERT_HEAD)(&s->blamed_commits, s->blamed_commit,
	    entry);
	memset(&s->blame, 0, sizeof(s->blame));
	s->first_line_onscreen = 1;
	s->last_line_onscreen = view->nlines;
	s->selected_line = 1;
	s->blame_complete = false;
	s->commit_id = commit_id;
	s->blame.origin = tip;
	s->blame.nlimit = nlimit;
	s->spin_idx = 0;
	s->colour = !fnc_init.nocolour && has_colors();

	if (s->colour) {
		rc = set_colours(&s->colours, FNC_VIEW_BLAME);
		if (rc)
			return rc;
	}

	view->show = show_blame_view;
	view->input = blame_input_handler;
	view->close = close_blame_view;
	view->search_init = blame_search_init;
	view->search_next = blame_search_next;

	return run_blame(view);
}

static int
run_blame(struct fnc_view *view)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_blame_view_state	*s = &view->state.blame;
	struct fnc_blame		*blame = &s->blame;
	fsl_deck			 d = fsl_deck_empty;
	fsl_buffer			 buf = fsl_buffer_empty;
	fsl_annotate_opt		*opt = NULL;
	const fsl_card_F		*cf;
	char				*filepath = NULL;
	char				*master = NULL, *root = NULL;
	int				 rc = 0;

	/*
	 * Trim prefixed '/' if path has been processed by map_repo_path(),
	 * which only occurs when the -c option has not been passed.
	 * XXX This slash trimming is cumbersome; we should not prefix a slash
	 * in map_repo_path() as we only want the slash for displaying an
	 * absolute-repository-relative path, so we should prefix it only then.
	 */
	filepath = s->path[0] != '/' ? s->path : s->path + 1;

	rc = fsl_deck_load_sym(f, &d, s->blamed_commit->id, FSL_SATYPE_CHECKIN);
	if (rc)
		goto end;

	cf = fsl_deck_F_search(&d, filepath);
	if (cf == NULL) {
		rc = RC(FSL_RC_NOT_FOUND, "'%s' not found in tree [%s]",
		    filepath, s->blamed_commit->id);
		goto end;
	}
	rc = fsl_card_F_content(f, cf, &buf);
	if (rc)
		goto end;

	/*
	 * We load f with the actual file content to map line offsets so we
	 * accurately find tokens when running a search.
	 */
	blame->f = tmpfile();
	if (blame->f == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "tmpfile");
		goto end;
	}

	opt = &blame->thread_cx.blame_opt;
	opt->filename = fsl_strdup(filepath);
	fcli_fax((char *)opt->filename);
	rc = fsl_sym_to_rid(f, s->blamed_commit->id, FSL_SATYPE_CHECKIN,
	    &opt->versionRid);
	if (rc)
		goto end;
	opt->originRid = blame->origin;    /* tip when -r is passed */
	if (blame->nlimit < 0)
		opt->limitMs = abs(blame->nlimit) * 1000;
	else
		opt->limitVersions = blame->nlimit;
	opt->out = blame_cb;
	opt->outState = &blame->cb_cx;

	rc = fnc_dump_buffer_to_file(&blame->filesz, &blame->nlines,
	    &blame->line_offsets, blame->f, &buf);
	if (rc)
		goto end;
	if (blame->nlines == 0) {
		s->blame_complete = true;
		goto end;
	}

	/* Don't include EOF \n in blame line count. */
	if (blame->line_offsets[blame->nlines - 1] == blame->filesz)
		--blame->nlines;

	blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
	if (blame->lines == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
		goto end;
	}

	master = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", NULL);
	if (master == NULL) {
		master = fsl_strdup("trunk");
		if (master == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	}
	root = fsl_mprintf("root:%s", master);
	rc = fsl_sym_to_uuid(f, root, FSL_SATYPE_CHECKIN,
	    &blame->cb_cx.root_commit, NULL);
	if (rc) {
		rc = RC(rc, "%s", "fsl_sym_to_uuid");
		goto end;
	}

	blame->cb_cx.view = view;
	blame->cb_cx.lines = blame->lines;
	blame->cb_cx.nlines = blame->nlines;
	blame->cb_cx.commit_id = fsl_strdup(s->blamed_commit->id);
	if (blame->cb_cx.commit_id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}
	blame->cb_cx.quit = &s->done;

	blame->thread_cx.path = s->path;
	blame->thread_cx.cb_cx = &blame->cb_cx;
	blame->thread_cx.complete = &s->blame_complete;
	blame->thread_cx.cancel_cb = cancel_blame;
	blame->thread_cx.cancel_cx = &s->done;
	s->blame_complete = false;

	if (s->first_line_onscreen + view->nlines - 1 > blame->nlines) {
		s->first_line_onscreen = 1;
		s->last_line_onscreen = view->nlines;
		s->selected_line = 1;
	}

end:
	fsl_free(master);
	fsl_free(root);
	fsl_deck_finalize(&d);
	fsl_buffer_clear(&buf);
	if (rc)
		stop_blame(blame);
	return rc;
}

/*
 * Write file content in buf to out file. Record the number of lines in the file
 * in nlines, and total bytes written in filesz. Assign byte offsets of each
 * line to the dynamically allocated *line_offsets, which must eventually be
 * disposed of by the caller. Flush and rewind out file when done.
 */
static int
fnc_dump_buffer_to_file(off_t *filesz, int *nlines, off_t **line_offsets,
    FILE *out, fsl_buffer *buf)
{
	off_t		 off = 0, total_len = 0;
	size_t		 len, n, i = 0, nalloc = 0;
	int		 rc = 0;
	const int	 alloc_chunksz = MIN(512, BUFSIZ);

	if (line_offsets)
		*line_offsets = NULL;
	if (filesz)
		*filesz = 0;
	if (nlines)
		*nlines = 0;

	len = buf->used;
	if (len == 0)
		return RC(FSL_RC_SIZE_MISMATCH, "%s",
		    "fnc_dump_buffer_to_file");
	if (nlines) {
		if (line_offsets && *line_offsets == NULL) {
			*nlines = 1;
			nalloc = alloc_chunksz;
			*line_offsets = calloc(nalloc, sizeof(**line_offsets));
			if (*line_offsets == NULL)
				return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
				    "%s", "calloc");

			/* Consume the first line. */
			while (i < len) {
				if (buf->mem[i] == '\n')
					break;
				++i;
			}
		}
		/* Scan '\n' offsets. */
		while (i < len) {
			if (buf->mem[i] != '\n') {
				++i;
				continue;
			}
			++(*nlines);
			if (line_offsets && nalloc < (size_t)*nlines) {
				size_t n, oldsz, newsz;
				off_t *new = NULL;

				n = *nlines + alloc_chunksz;
				oldsz = nalloc * sizeof(**line_offsets);
				newsz = n * sizeof(**line_offsets);
				if (newsz <= oldsz) {
					size_t b = oldsz - newsz;
					if (b < oldsz / 2 &&
					    b < (size_t)getpagesize()) {
						memset((char *)*line_offsets
						    + newsz, 0, b);
						goto allocated;
					}
				}
				new = fsl_realloc(*line_offsets, newsz);
				if (new == NULL) {
					fsl_free(*line_offsets);
					*line_offsets = NULL;
					return RC(FSL_RC_ERROR, "%s",
					    "fsl_realloc");
				}
				*line_offsets = new;
allocated:
				nalloc = n;
			}
			if (line_offsets) {
				off = total_len + i + 1;
				(*line_offsets)[*nlines - 1] = off;
			}
			++i;
		}
	}
	n = fwrite(buf->mem, 1, len, out);
	if (n != len)
		return RC(ferror(out) ? fsl_errno_to_rc(errno, FSL_RC_IO)
		    : FSL_RC_IO, "%s", "fwrite");
	total_len += len;

	if (fflush(out) != 0)
		return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fflush");
	rewind(out);

	if (filesz)
		*filesz = total_len;

	return rc;
}

static int
show_blame_view(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 rc = 0;

	if (!s->blame.thread_id && !s->blame_complete) {
		rc = pthread_create(&s->blame.thread_id, NULL, blame_thread,
		    &s->blame.thread_cx);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_create");

		halfdelay(1);	/* Fast refresh while annotating.  */
	}

	if (s->blame_complete)
		cbreak();	/* Return to blocking mode. */

	rc = draw_blame(view);
	draw_vborder(view);

	return rc;
}

static void *
blame_thread(void *state)
{
	struct fnc_blame_thread_cx	*cx = state;
	int				 rc0, rc;

	rc = block_main_thread_signals();
	if (rc)
		return (void *)(intptr_t)rc;

	rc = fsl_annotate(fcli_cx(), &cx->blame_opt);
	if (rc && fsl_cx_err_get_e(fcli_cx())->code == FSL_RC_BREAK) {
		fcli_err_reset();
		rc = 0;
	}

	rc0 = pthread_mutex_lock(&fnc_mutex);
	if (rc0)
		return (void *)(intptr_t)RC(fsl_errno_to_rc(rc0, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	*cx->complete = true;

	rc0 = pthread_mutex_unlock(&fnc_mutex);
	if (rc0 && !rc)
		rc = RC(fsl_errno_to_rc(rc0, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");

	return (void *)(intptr_t)rc;
}

static int
blame_cb(void *state, fsl_annotate_opt const * const opt,
    fsl_annotate_step const * const step)
{
	struct fnc_blame_cb_cx	*cx = state;
	struct fnc_blame_line	*line;
	int			 rc = 0;

	rc = pthread_mutex_lock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	if (*cx->quit) {
		rc = fcli_err_set(FSL_RC_BREAK, "user quit");
		goto end;
	}

	line = &cx->lines[step->lineNumber - 1];
	if (line->annotated)
		goto end;

	if (step->mtime) {
		line->id = fsl_strdup(step->versionHash);
		if (line->id == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", fsl_strdup);
			goto end;
		}
		line->annotated = true;
	} else
		line->id = NULL;

	/* -r can return lines with no version, so use root check-in. */
	if (opt->originRid && !line->id) {
		line->id = fsl_strdup(cx->root_commit);
		line->annotated = true;
	}

	++cx->nlines;
end:
	rc = pthread_mutex_unlock(&fnc_mutex);
	if (rc)
		rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");
	return rc;
}

static int
draw_blame(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	struct fnc_blame		*blame = &s->blame;
	struct fnc_blame_line		*blame_line;
	regmatch_t			*regmatch = &view->regmatch;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	char				*line = NULL;
	fsl_uuid_str			 prev_id = NULL, id_str = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 width, lineno = 0, nprinted = 0;
	int				 rc = 0;
	const int			 idfield = 11;  /* Prefix + space. */

	id_str = fsl_strdup(s->blamed_commit->id);
	if (id_str == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");

	rewind(blame->f);
	werase(view->window);

	if ((line = fsl_mprintf("checkin %s", id_str)) == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "fsl_mprintf");
		fsl_free(id_str);
		return rc;
	}

	rc = formatln(&wcstr, &width, line, view->ncols, 0);
	fsl_free(line);
	line = NULL;
	if (rc)
		return rc;
	if (screen_is_shared(view))
		wstandout(view->window);
	if (s->colour)
		c = get_colour(&s->colours, FNC_COMMIT_ID);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, wcstr);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	if (screen_is_shared(view))
		wstandend(view->window);
	fsl_free(wcstr);
	wcstr = NULL;
	if (width < view->ncols - 1)
		waddch(view->window, '\n');

	if ((line = fsl_mprintf("[%d/%d] %s%s%s %c",
	    s->first_line_onscreen - 1 + s->selected_line, blame->nlines,
	    s->blame_complete ? "" : "annotating... ",
	    fnc_init.sym ? "/" : "", s->path,
	    s->blame_complete ? ' ' : SPINNER[s->spin_idx])) == NULL) {
		fsl_free(id_str);
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "fsl_mprintf");
	}
	if (SPINNER[++s->spin_idx] == '\0')
		s->spin_idx = 0;
	fsl_free(id_str);
	rc = formatln(&wcstr, &width, line, view->ncols, 0);
	fsl_free(line);
	line = NULL;
	if (rc)
		return rc;
	waddwstr(view->window, wcstr);
	fsl_free(wcstr);
	wcstr = NULL;
	if (width < view->ncols - 1)
		waddch(view->window, '\n');

	s->eof = false;
	while (nprinted < view->nlines - 2) {
		linelen = getline(&line, &linesz, blame->f);
		if (linelen == -1) {
			if (feof(blame->f)) {
				s->eof = true;
				break;
			}
			fsl_free(line);
			return RC(ferror(blame->f) ? fsl_errno_to_rc(errno,
			    FSL_RC_IO) : FSL_RC_IO, "%s", "getline");
		}
		if (++lineno < s->first_line_onscreen)
			continue;

		if (view->active && nprinted == s->selected_line - 1)
			wattr_on(view->window, A_REVERSE, NULL);

		if (blame->nlines > 0) {
			blame_line = &blame->lines[lineno - 1];
			if (blame_line->annotated && prev_id &&
			    fsl_uuidcmp(prev_id, blame_line->id) == 0 &&
			    !(view->active &&
			    nprinted == s->selected_line - 1)) {
				waddstr(view->window, "          ");
			} else if (blame_line->annotated) {
				char *id_str;
				id_str = fsl_strndup(blame_line->id,
				    idfield - 1);
				if (id_str == NULL) {
					fsl_free(line);
					return RC(FSL_RC_ERROR, "%s",
					    "fsl_strdup");
				}
				if (s->colour)
					c = get_colour(&s->colours,
					    FNC_COMMIT_ID);
				if (c)
					wattr_on(view->window,
					    COLOR_PAIR(c->scheme), NULL);
				wprintw(view->window, "%.*s", idfield - 1,
				    id_str);
				if (c)
					wattr_off(view->window,
					    COLOR_PAIR(c->scheme), NULL);
				fsl_free(id_str);
				prev_id = blame_line->id;
			} else {
				waddstr(view->window, "..........");
				prev_id = NULL;
			}
		} else {
			waddstr(view->window, "..........");
			prev_id = NULL;
		}

		if (view->active && nprinted == s->selected_line - 1)
			wattr_off(view->window, A_REVERSE, NULL);
		waddstr(view->window, " ");

		if (view->ncols <= idfield) {
			width = idfield;
			wcstr = wcsdup(L"");
			if (wcstr == NULL) {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE),
				    "%s", "wcsdup");
				fsl_free(line);
				return rc;
			}
		} else if (s->first_line_onscreen + nprinted == s->matched_line
		    && regmatch->rm_so >= 0 &&
		    regmatch->rm_so < regmatch->rm_eo) {
			rc = write_matched_line(&width, line,
			    view->ncols - idfield, idfield,
			    view->window, regmatch);
			if (rc) {
				fsl_free(line);
				return rc;
			}
			width += idfield;
		} else {
			rc = formatln(&wcstr, &width, line,
			    view->ncols - idfield, idfield);
			waddwstr(view->window, wcstr);
			fsl_free(wcstr);
			wcstr = NULL;
			width += idfield;
		}

		if (width <= view->ncols - 1)
			waddch(view->window, '\n');
		if (++nprinted == 1)
			s->first_line_onscreen = lineno;
	}
	fsl_free(line);
	s->last_line_onscreen = lineno;

	draw_vborder(view);

	return rc;
}

static int
blame_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_view			*diff_view;
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 start_col = 0, rc = 0;

	switch (ch) {
	case 'q':
		s->done = true;
		if (s->selected_commit)
			fnc_commit_artifact_close(s->selected_commit);
		break;
	case 'c':
		s->colour = !s->colour;
		break;
	case 'g':
		if (!fnc_home(view))
			break;
	case KEY_HOME:
		s->selected_line = 1;
		s->first_line_onscreen = 1;
		break;
	case KEY_END:
	case 'G':
		if (s->blame.nlines < view->nlines - 2) {
			s->selected_line = s->blame.nlines;
			s->first_line_onscreen = 1;
		} else {
			s->selected_line = view->nlines - 2;
			s->first_line_onscreen = s->blame.nlines -
			    (view->nlines - 3);
		}
		break;
	case KEY_UP:
	case 'k':
		if (s->selected_line > 1)
			--s->selected_line;
		else if (s->selected_line == 1 && s->first_line_onscreen > 1)
			--s->first_line_onscreen;
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->first_line_onscreen == 1) {
			s->selected_line = 1;
			break;
		}
		if (s->first_line_onscreen > view->nlines - 2)
			s->first_line_onscreen -= (view->nlines - 2);
		else
			s->first_line_onscreen = 1;
		break;
	case KEY_DOWN:
	case 'j':
		if (s->selected_line < view->nlines - 2 &&
		    s->first_line_onscreen +
		    s->selected_line <= s->blame.nlines)
			++s->selected_line;
		else if (s->last_line_onscreen < s->blame.nlines)
			++s->first_line_onscreen;
		break;
	case 'b':
	case 'p': {
		fsl_uuid_cstr id = NULL;
		id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
		    s->first_line_onscreen, s->selected_line);
		if (id == NULL)
			break;
		if (ch == 'p') {
			fsl_cx		*f = fcli_cx();
			fsl_db		*db = fsl_needs_repo(f);
			fsl_deck	 d = fsl_deck_empty;
			fsl_id_t	 rid = fsl_uuid_to_rid(f, id);
			fsl_uuid_str	 pid = fsl_db_g_text(db, NULL,
			    "SELECT uuid FROM plink, blob WHERE plink.cid=%d "
			    "AND blob.rid=plink.pid AND plink.isprim", rid);
			if (pid == NULL)
				break;
			/* Check file exists in parent check-in. */
			rc = fsl_deck_load_sym(f, &d, pid, FSL_SATYPE_CHECKIN);
			if (rc) {
				fsl_deck_finalize(&d);
				fsl_free(pid);
				return RC(rc, "%s", "fsl_deck_load_sym");
			}
			rc = fsl_deck_F_rewind(&d);
			if (rc) {
				fsl_deck_finalize(&d);
				fsl_free(pid);
				return RC(rc, "%s", "fsl_deck_F_rewind");
			}
			if (fsl_deck_F_search(&d, s->path +
			    (fnc_init.sym ? 0 : 1)) == NULL) {
				char *m = fsl_mprintf("-- %s not in [%.12s] --",
				    s->path + (fnc_init.sym ? 0 : 1), pid);
				if (m == NULL)
					rc = RC(FSL_RC_ERROR, "%s",
					    "fsl_mprintf");
				wattr_on(view->window, A_BOLD, NULL);
				mvwaddstr(view->window,
				    view->start_ln + view->nlines - 1, 0, m);
				wclrtoeol(view->window);
				wattr_off(view->window, A_BOLD, NULL);
				update_panels();
				doupdate();
				sleep(1);
				fsl_deck_finalize(&d);
				fsl_free(pid);
				fsl_free(m);
				break;
			}
			rc = fnc_commit_qid_alloc(&s->blamed_commit, pid);
			if (rc)
				return rc;
		} else {
			if (!fsl_uuidcmp(id, s->blamed_commit->id))
				break;
			rc = fnc_commit_qid_alloc(&s->blamed_commit, id);
		}
		if (rc)
			break;
		s->done = true;
		rc = stop_blame(&s->blame);
		s->done = false;
		if (rc)
			break;
		CONCAT(STAILQ, _INSERT_HEAD)(&s->blamed_commits,
		    s->blamed_commit, entry);
		rc = run_blame(view);
		if (rc)
			break;
		break;
	}
	case KEY_BACKSPACE:
	case 'B': {
		struct fnc_commit_qid *first;
		first = CONCAT(STAILQ, _FIRST)(&s->blamed_commits);
		if (!fsl_uuidcmp(first->id, s->commit_id))
			break;
		s->done = true;
		rc = stop_blame(&s->blame);
		s->done = false;
		if (rc)
			break;
		CONCAT(STAILQ, _REMOVE_HEAD)(&s->blamed_commits, entry);
		fnc_commit_qid_free(s->blamed_commit);
		s->blamed_commit = CONCAT(STAILQ, _FIRST)(&s->blamed_commits);
		rc = run_blame(view);
		if (rc)
			break;
		break;
	}
	case KEY_ENTER:
	case '\r': {
		fsl_cx				*f = fcli_cx();
		struct fnc_commit_artifact	*commit = NULL;
		fsl_stmt			*q = NULL;
		fsl_uuid_cstr			 id = NULL;

		id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
		    s->first_line_onscreen, s->selected_line);
		if (id == NULL)
			break;
		if (s->selected_commit)
			fnc_commit_artifact_close(s->selected_commit);
		if (rc)
			break;
		q = fsl_stmt_malloc();
		rc = commit_builder(&commit, fsl_uuid_to_rid(f, id), q);
		fsl_stmt_finalize(q);
		if (rc) {
			fnc_commit_artifact_close(commit);
			break;
		}
		if (view_is_parent(view))
		    start_col = view_split_start_col(view->start_col);
		diff_view = view_open(0, 0, 0, start_col, FNC_VIEW_DIFF);
		if (diff_view == NULL) {
			fnc_commit_artifact_close(commit);
			rc = RC(FSL_RC_ERROR, "%s", "view_open");
			break;
		}
		rc = open_diff_view(diff_view, commit, DIFF_DEF_CTXT,
		    fnc_init.ws, fnc_init.invert, !fnc_init.quiet, NULL, true,
		    NULL);
		s->selected_commit = commit;
		if (rc) {
			fnc_commit_artifact_close(commit);
			view_close(diff_view);
			break;
		}
		view->active = false;
		diff_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				break;
			view_set_child(view, diff_view);
			view->focus_child = true;
		} else
			*new_view = diff_view;
		if (rc)
			break;
		break;
	}
	case KEY_NPAGE:
	case CTRL('f'):
	case ' ':
		if (s->last_line_onscreen >= s->blame.nlines && s->selected_line
		    >= MIN(s->blame.nlines, view->nlines - 2))
			break;
		if (s->last_line_onscreen >= s->blame.nlines &&
		    s->selected_line < view->nlines - 2) {
			s->selected_line = MIN(s->blame.nlines,
			    view->nlines - 2);
			break;
		}
		if (s->last_line_onscreen + view->nlines - 2 <= s->blame.nlines)
			s->first_line_onscreen += view->nlines - 2;
		else
			s->first_line_onscreen =
			    s->blame.nlines - (view->nlines - 3);
		break;
	case KEY_RESIZE:
		if (s->selected_line > view->nlines - 2) {
			s->selected_line = MIN(s->blame.nlines,
			    view->nlines - 2);
		}
		break;
	default:
		break;
	}
	return rc;
}

static int
blame_search_init(struct fnc_view *view)
{
	struct fnc_blame_view_state *s = &view->state.blame;

	s->matched_line = 0;
	return 0;
}

static int
blame_search_next(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	char				*line = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 lineno;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
		return 0;
	}

	if (s->matched_line) {
		if (view->searching == SEARCH_FORWARD)
			lineno = s->matched_line + 1;
		else
			lineno = s->matched_line - 1;
	} else {
		if (view->searching == SEARCH_FORWARD)
			lineno = 1;
		else
			lineno = s->blame.nlines;
	}

	while (1) {
		off_t offset;

		if (lineno <= 0 || lineno > s->blame.nlines) {
			if (s->matched_line == 0) {
				view->search_status = SEARCH_CONTINUE;
				break;
			}

			if (view->searching == SEARCH_FORWARD)
				lineno = 1;
			else
				lineno = s->blame.nlines;
		}

		offset = s->blame.line_offsets[lineno - 1];
		if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
			fsl_free(line);
			return RC(fsl_errno_to_rc(errno, FSL_RC_IO),
			    "%s", "fseeko");
		}
		linelen = getline(&line, &linesz, s->blame.f);
		if (linelen != -1 && regexec(&view->regex, line, 1,
		    &view->regmatch, 0) == 0) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_line = lineno;
			break;
		}
		if (view->searching == SEARCH_FORWARD)
			++lineno;
		else
			--lineno;
	}
	fsl_free(line);

	if (s->matched_line) {
		s->first_line_onscreen = s->matched_line;
		s->selected_line = 1;
	}

	return 0;
}

static fsl_uuid_cstr
get_selected_commit_id(struct fnc_blame_line *lines, int nlines,
    int first_line_onscreen, int selected_line)
{
	struct fnc_blame_line *line;

	if (nlines <= 0)
		return NULL;

	line = &lines[first_line_onscreen - 1 + selected_line - 1];

	return line->id;
}

static int
fnc_commit_qid_alloc(struct fnc_commit_qid **qid, fsl_uuid_cstr id)
{
	int rc = 0;

	*qid = calloc(1, sizeof(**qid));
	if (*qid == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	(*qid)->id = fsl_strdup(id);
	if ((*qid)->id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		fnc_commit_qid_free(*qid);
		*qid = NULL;
	}

	return rc;
}

static int
close_blame_view(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	struct fsl_list_state		 st = { FNC_COLOUR_OBJ };
	int				 rc = 0;

	rc = stop_blame(&s->blame);

	while (!CONCAT(STAILQ, _EMPTY)(&s->blamed_commits)) {
		struct fnc_commit_qid *blamed_commit;
		blamed_commit = CONCAT(STAILQ, _FIRST)(&s->blamed_commits);
		CONCAT(STAILQ, _REMOVE_HEAD)(&s->blamed_commits, entry);
		fnc_commit_qid_free(blamed_commit);
	}

	fsl_free(s->path);
	fsl_list_clear(&s->colours, fsl_list_object_free, &st);

	return rc;
}

static int
stop_blame(struct fnc_blame *blame)
{
	int idx, rc = 0;

	if (blame->thread_id) {
		int retval;
		rc = pthread_mutex_unlock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		rc = pthread_join(blame->thread_id, (void **)&retval);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_join");
		rc = pthread_mutex_lock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		if (!rc && fsl_cx_err_get_e(fcli_cx())->code == FSL_RC_BREAK) {
			rc = 0;
			fcli_err_reset();
		}
		blame->thread_id = 0;
	}
	if (blame->f) {
		if (fclose(blame->f) == EOF && rc == 0)
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s",
			    fclose);
		blame->f = NULL;
	}
	if (blame->lines) {
		for (idx = 0; idx < blame->nlines; ++idx)
			fsl_free(blame->lines[idx].id);
		fsl_free(blame->lines);
		blame->lines = NULL;
	}

	fsl_free(blame->cb_cx.root_commit);
	blame->cb_cx.root_commit = NULL;
	fsl_free(blame->cb_cx.commit_id);
	blame->cb_cx.commit_id = NULL;
	fsl_free(blame->line_offsets);

	return rc;
}

static int
cancel_blame(void *state)
{
	int	*done = state;
	int	 rc = 0;

	rc = pthread_mutex_lock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");

	if (*done)
		rc = fcli_err_set(FSL_RC_BREAK, "user quit");

	rc = pthread_mutex_unlock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	return rc;
}

static void
fnc_commit_qid_free(struct fnc_commit_qid *qid)
{
	fsl_free(qid->id);
	fsl_free(qid);
}

static int
cmd_branch(fcli_command const *argv)
{
	struct fnc_view	*view;
	char		*glob = NULL;
	double		 dateline;
	int		 branch_flags, rc = 0, when = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	branch_flags = BRANCH_LS_OPEN_CLOSED;
	if (fnc_init.open && fnc_init.closed)
		return RC(FSL_RC_MISUSE, "%s",
		    "--open and --close are mutually exclusive options");
	else if (fnc_init.open)
		branch_flags = BRANCH_LS_OPEN_ONLY;
	else if (fnc_init.closed)
		branch_flags = BRANCH_LS_CLOSED_ONLY;

	if (fnc_init.sort) {
		if (!fsl_strcmp(fnc_init.sort, "mru"))
			FLAG_SET(branch_flags, BRANCH_SORT_MTIME);
		else if (!fsl_strcmp(fnc_init.sort, "state"))
			FLAG_SET(branch_flags, BRANCH_SORT_STATUS);
		else
			return RC(FSL_RC_MISUSE, "invalid sort order: %s",
			    fnc_init.sort);
	}
	if (fnc_init.noprivate)
		FLAG_SET(branch_flags, BRANCH_LS_NO_PRIVATE);
	if (fnc_init.reverse)
		FLAG_SET(branch_flags, BRANCH_SORT_REVERSE);

	if (fnc_init.after && fnc_init.before) {
		return RC(FSL_RC_MISUSE, "%s",
		    "--before and --after are mutually exclusive options");
	} else if (fnc_init.after || fnc_init.before) {
		const char *d = NULL;
		d = fnc_init.after ? fnc_init.after : fnc_init.before;
		when = fnc_init.after ? 1 : -1;
		rc = fnc_date_to_mtime(&dateline, d, when);
		if (rc)
			return rc;
	}
	glob = fsl_strdup(fcli_next_arg(true));

	init_curses();

	view = view_open(0, 0, 0, 0, FNC_VIEW_BRANCH);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_branch_view(view, branch_flags, glob, dateline, when);
	if (rc)
		goto end;

	rc = view_loop(view);
end:
	fnc_free_branches(&view->state.branch);
	fsl_free(glob);
	return rc;
}

static int
open_branch_view(struct fnc_view *view, int branch_flags, const char *glob,
    double dateline, int when)
{
	struct fnc_branch_view_state	*s = &view->state.branch;
	int				 rc = 0;

	s->selected_branch = 0;
	s->colour = !fnc_init.nocolour && has_colors();
	s->branch_flags = branch_flags;
	s->branch_glob = glob;
	s->dateline = dateline;
	s->when = when;

	rc = fnc_load_branches(s);
	if (rc)
		return rc;

	if (s->colour)
		init_pair(FNC_COMMIT_ID, COLOR_GREEN, -1);

	view->show = show_branch_view;
	view->input = branch_input_handler;
	view->close = close_branch_view;
	view->search_init = branch_search_init;
	view->search_next = branch_search_next;

	return 0;
}

static int
fnc_load_branches(struct fnc_branch_view_state *s)
{
	fsl_cx		*const f = fcli_cx();
	fsl_buffer	 sql = fsl_buffer_empty;
	fsl_stmt	*stmt = NULL;
	char		*curr_branch = NULL;
	fsl_id_t	 ckoutrid;
	int		 rc = 0;

	rc = create_tmp_branchlist_table();
	if (rc)
		goto end;

	TAILQ_INIT(&s->branches);
	s->nbranches = 0;

	switch (FLAG_CHK(s->branch_flags, BRANCH_LS_BITMASK)) {
	case BRANCH_LS_OPEN_CLOSED:
		rc = fsl_buffer_append(&sql,
		    "SELECT name, isprivate, isclosed, mtime"
		    " FROM tmp_brlist WHERE 1", -1);
		break;
	case BRANCH_LS_OPEN_ONLY:
		rc = fsl_buffer_append(&sql,
		    "SELECT name, isprivate, isclosed, mtime"
		    " FROM tmp_brlist WHERE NOT isclosed", -1);
		break;
	case BRANCH_LS_CLOSED_ONLY:
		rc = fsl_buffer_append(&sql,
		    "SELECT name, isprivate, isclosed, mtime"
		    " FROM tmp_brlist WHERE isclosed", -1);
		break;
	}
	if (rc)
		goto end;

	if (s->branch_glob) {
		char *like = fsl_mprintf("%%%%%s%%%%", s->branch_glob);
		rc = fsl_buffer_appendf(&sql, " AND name LIKE %Q", like);
		fsl_free(like);
	}
	if (FLAG_CHK(s->branch_flags, BRANCH_LS_NO_PRIVATE))
		rc = fsl_buffer_append(&sql, " AND NOT isprivate", -1);
	if (FLAG_CHK(s->branch_flags, BRANCH_SORT_MTIME))
		rc = fsl_buffer_append(&sql, " ORDER BY -mtime", -1);
	else if (FLAG_CHK(s->branch_flags, BRANCH_SORT_STATUS))
		rc = fsl_buffer_append(&sql, " ORDER BY isclosed", -1);
	else
		rc = fsl_buffer_append(&sql, " ORDER BY name COLLATE nocase",
		    -1);

	if (!rc && (FLAG_CHK(s->branch_flags, BRANCH_SORT_REVERSE)))
		rc = fsl_buffer_append(&sql," DESC", -1);

	stmt = fsl_stmt_malloc();
	if (stmt == NULL)
		goto end;
	if (!rc)
		rc = fsl_cx_prepare(f, stmt, fsl_buffer_cstr(&sql));

	fsl_ckout_version_info(f, &ckoutrid, NULL);
	curr_branch = fsl_db_g_text(fsl_needs_repo(f), NULL,
	    "SELECT value FROM tagxref WHERE rid=%d AND tagid=%d", ckoutrid, 8);

	while (fsl_stmt_step(stmt) == FSL_RC_STEP_ROW) {
		struct fnc_branch *new_branch;
		struct fnc_branchlist_entry *be;
		const char *brname = fsl_stmt_g_text(stmt, 0, NULL);
		bool private = (curr_branch && fsl_stmt_g_int32(stmt, 1) == 1);
		bool open = fsl_stmt_g_int32(stmt, 2) == 0;
		double mtime = fsl_stmt_g_int64(stmt, 3);
		bool curr = curr_branch && !fsl_strcmp(curr_branch, brname);
		if ((s->when > 0 && mtime < s->dateline) ||
		    (s->when < 0 && mtime > s->dateline))
			continue;
		alloc_branch(&new_branch, brname, mtime, open, private, curr);
		fnc_branchlist_insert(&be, &s->branches, new_branch);
		if (be)
			be->idx = s->nbranches++;
	}
	s->first_branch_onscreen = TAILQ_FIRST(&s->branches);

	if (!stmt->rowCount)
		rc = RC(FSL_RC_BREAK, "no matching records: %s",
		    s->branch_glob);
end:
	fsl_stmt_finalize(stmt);
	fsl_free(curr_branch);
	fsl_buffer_clear(&sql);
	return rc;
}

static int
create_tmp_branchlist_table(void)
{
	fsl_cx			*const f = fcli_cx();
	fsl_db			*db = fsl_needs_ckout(f);
	static const char	 tmp_branchlist_table[] =
	    "CREATE TEMP TABLE IF NOT EXISTS tmp_brlist AS "
	    "SELECT tagxref.value AS name,"
	    " max(event.mtime) AS mtime,"
	    " EXISTS(SELECT 1 FROM tagxref AS tx WHERE tx.rid=tagxref.rid"
	    "  AND tx.tagid=(SELECT tagid FROM tag WHERE tagname='closed')"
	    "  AND tx.tagtype > 0) AS isclosed,"
	    " (SELECT tagxref.value FROM plink CROSS JOIN tagxref"
	    "  WHERE plink.pid=event.objid"
	    "  AND tagxref.rid=plink.cid"
	    "  AND tagxref.tagid=(SELECT tagid FROM tag WHERE tagname='branch')"
	    "  AND tagtype>0) AS mergeto,"
	    " count(*) AS nckin,"
	    " (SELECT uuid FROM blob WHERE rid=tagxref.rid) AS ckin,"
	    " event.bgcolor AS bgclr,"
	    " EXISTS(SELECT 1 FROM private WHERE rid=tagxref.rid) AS isprivate "
	    "FROM tagxref, tag, event "
	    "WHERE tagxref.tagid=tag.tagid"
	    " AND tagxref.tagtype>0"
	    " AND tag.tagname='branch'"
	    " AND event.objid=tagxref.rid "
	    "GROUP BY 1;";
	int rc = 0;

	if (!db)
		return RC(FSL_RC_NOT_A_CKOUT, "%s", "fsl_needs_ckout");
	rc = fsl_db_exec(db, tmp_branchlist_table);

	return rc ? RC(fsl_cx_uplift_db_error2(f, db, rc), "%s", "fsl_db_exec")
	    : rc;
}

static int
alloc_branch(struct fnc_branch **branch, const char *name, double mtime,
    bool open, bool priv, bool curr)
{
	fsl_uuid_str	id = NULL;
	char		iso8601[ISO8601_TIMESTAMP], *date = NULL;
	int		rc = 0;

	*branch = calloc(1, sizeof(**branch));
	if (*branch == NULL)
		return RC(FSL_RC_ERROR, "%s", "calloc");

	rc = fsl_sym_to_uuid(fcli_cx(), name, FSL_SATYPE_ANY, &id, NULL);
	if (rc || id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_sym_to_uuid");
		fnc_branch_close(*branch);
		*branch = NULL;
		return rc;
	}

	fsl_julian_to_iso8601(mtime, iso8601, false);
	date = fsl_mprintf("%.*s", ISO8601_DATE_ONLY, iso8601);

	(*branch)->id = id;
	(*branch)->name = fsl_strdup(name);
	(*branch)->date = date;
	(*branch)->open = open;
	(*branch)->private = priv;
	(*branch)->current = curr;
	if ((*branch)->name == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		fnc_branch_close(*branch);
		*branch = NULL;
	}

	return rc;
}

static int
fnc_branchlist_insert(struct fnc_branchlist_entry **newp,
    struct fnc_branchlist_head *branches, struct fnc_branch *branch)
{
	struct fnc_branchlist_entry *new, *be;

	*newp = NULL;

	new = fsl_malloc(sizeof(*new));
	if (new == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	new->branch = branch;
	*newp = new;

	be = TAILQ_LAST(branches, fnc_branchlist_head);
	if (!be) {
		/* Empty list; add first branch. */
		TAILQ_INSERT_HEAD(branches, new, entries);
		return 0;
	}

	/*
	 * Deduplicate (extremely unlikely or impossible?) entries on insert.
	 * Don't force lexicographical order; we already retrieved the branch
	 * names from the database using a query to obtain (a) lexicographical
	 * or (b) user-specified sorted results (i.e., MRU or LRU).
	 */
	while (be) {
		if (!fsl_strcmp(be->branch->name, new->branch->name)) {
			/* Duplicate entry. */
			fsl_free(new);
			*newp = NULL;
			return 0;
		}
		be = TAILQ_PREV(be, fnc_branchlist_head, entries);
	}

	/* No duplicates; add to end of list. */
	TAILQ_INSERT_TAIL(branches, new, entries);
	return 0;
}

static int
show_branch_view(struct fnc_view *view)
{
	struct fnc_branch_view_state	*s = &view->state.branch;
	struct fnc_branchlist_entry	*be;
	char				*line = NULL;
	wchar_t				*wline;
	int				 limit, n, width, rc = 0;

	werase(view->window);
	s->ndisplayed = 0;

	limit = view->nlines;
	if (limit == 0)
		return rc;

	be = s->first_branch_onscreen;

	if ((line = fsl_mprintf("branches [%d/%d]", be->idx + s->selected + 1,
	    s->nbranches)) == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");

	rc = formatln(&wline, &width, line, view->ncols, 0);
	if (rc) {
		fsl_free(line);
		return rc;
	}
	if (screen_is_shared(view))
		wstandout(view->window);
	waddwstr(view->window, wline);
	if (screen_is_shared(view))
		wstandend(view->window);
	fsl_free(wline);
	wline = NULL;
	fsl_free(line);
	line = NULL;
	if (width < view->ncols - 1)
		waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;

	n = 0;
	while (be && limit > 0) {
		char *line = NULL;

		line = fsl_mprintf(" %c%s%s%s%s%s%s%c %s",
		    be->branch->open ? '+' : '-', be->branch->name,
		    be->branch->private ? "*" : "",
		    be->branch->current ? "@" : "", s->show_id ?  " [" : "",
		    s->show_id ? be->branch->id : "", s->show_id ? "]" : "",
		    s->show_date ? ':' : 0,
		    s->show_date ? be->branch->date : 0);
		if (line == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");

		rc = formatln(&wline, &width, line, view->ncols, 0);
		if (rc) {
			fsl_free(line);
			return rc;
		}

		if (n == s->selected) {
			if (view->active)
				wattr_on(view->window, A_REVERSE, NULL);
			s->selected_branch = be;
		}
		if (s->colour)
			wattr_on(view->window, COLOR_PAIR(FNC_COMMIT_ID), NULL);
		waddwstr(view->window, wline);
		if (s->colour)
			wattr_off(view->window, COLOR_PAIR(FNC_COMMIT_ID), NULL);
		if (width < view->ncols - 1)
			waddch(view->window, '\n');
		if (n == s->selected && view->active)
			wattr_off(view->window, A_REVERSE, NULL);

		fsl_free(line);
		fsl_free(wline);
		wline = NULL;
		++n;
		++s->ndisplayed;
		--limit;
		s->last_branch_onscreen = be;
		be = TAILQ_NEXT(be, entries);
	}

	draw_vborder(view);
	return rc;
}

static int
branch_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_branch_view_state	*s = &view->state.branch;
	struct fnc_view			*timeline_view, *tree_view;
	struct fnc_branchlist_entry	*be;
	int				 start_col = 0, n, rc = 0;

	switch (ch) {
	case 'c':
		s->colour = !s->colour;
		break;
	case 'd':
		s->show_date = !s->show_date;
		break;
	case 'i':
		s->show_id = !s->show_id;
		break;
	case KEY_ENTER:
	case '\r':
	case ' ':
		if (!s->selected_branch)
			break;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		rc = tl_branch_entry(&timeline_view, start_col,
		    s->selected_branch);
		view->active = false;
		timeline_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				return rc;
			view_set_child(view, timeline_view);
			view->focus_child = true;
		} else
			*new_view = timeline_view;
		break;
	case 't':
		if (!s->selected_branch)
			break;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		rc = browse_branch_tree(&tree_view, start_col,
		    s->selected_branch);
		if (rc || tree_view == NULL)
			break;
		view->active = false;
		tree_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				return rc;
			view_set_child(view, tree_view);
			view->focus_child = true;
		} else
			*new_view = tree_view;
		break;
	case 'g':
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	case KEY_HOME:
		s->selected = 0;
		s->first_branch_onscreen = TAILQ_FIRST(&s->branches);
		break;
	case KEY_END:
	case 'G':
		s->selected = 0;
		be = TAILQ_LAST(&s->branches, fnc_branchlist_head);
		for (n = 0; n < view->nlines - 1; ++n) {
			if (be == NULL)
				break;
			s->first_branch_onscreen = be;
			be = TAILQ_PREV(be, fnc_branchlist_head, entries);
		}
		if (n > 0)
			s->selected = n - 1;
		break;
	case KEY_UP:
	case 'k':
		if (s->selected > 0) {
			--s->selected;
			break;
		}
		branch_scroll_up(s, 1);
		break;
	case KEY_DOWN:
	case 'j':
		if (s->selected < s->ndisplayed - 1) {
			++s->selected;
			break;
		}
		if (TAILQ_NEXT(s->last_branch_onscreen, entries) == NULL)
			/* Reached last entry. */
			break;
		branch_scroll_down(s, 1);
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->first_branch_onscreen == TAILQ_FIRST(&s->branches))
			s->selected = 0;
		branch_scroll_up(s, MAX(0, view->nlines - 1));
		break;
	case KEY_NPAGE:
	case CTRL('f'):
		if (TAILQ_NEXT(s->last_branch_onscreen, entries) == NULL) {
			/* No more entries off-page; move cursor down. */
			if (s->selected < s->ndisplayed - 1)
				s->selected = s->ndisplayed - 1;
			break;
		}
		branch_scroll_down(s, view->nlines - 1);
		break;
	case CTRL('l'):
	case 'R':
		fnc_free_branches(s);
		s->branch_glob = NULL; /* Shared pointer. */
		s->when = 0;
		s->branch_flags = BRANCH_LS_OPEN_CLOSED;
		rc = fnc_load_branches(s);
		break;
	case KEY_RESIZE:
		if (view->nlines >= 2 && s->selected >= view->nlines - 1)
			s->selected = view->nlines - 2;
		break;
	default:
		break;
	}

	return rc;
}

static int
tl_branch_entry(struct fnc_view **new_view, int start_col,
    struct fnc_branchlist_entry *be)
{
	struct fnc_view	*timeline_view;
	fsl_id_t	 rid;
	int		 rc = 0;

	*new_view = NULL;

	rid = fsl_uuid_to_rid(fcli_cx(), be->branch->id);
	if (rid < 0)
		return RC(rc, "%s", "fsl_uuid_to_rid");

	timeline_view = view_open(0, 0, 0, start_col, FNC_VIEW_TIMELINE);
	if (timeline_view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_timeline_view(timeline_view, rid, "/");
end:
	if (rc)
		view_close(timeline_view);
	else
		*new_view = timeline_view;
	return rc;
}

static int
browse_branch_tree(struct fnc_view **new_view, int start_col,
    struct fnc_branchlist_entry *be)
{
	struct fnc_view	*tree_view;
	fsl_id_t	 rid;
	int		 rc = 0;

	*new_view = NULL;

	rid = fsl_uuid_to_rid(fcli_cx(), be->branch->id);
	if (rid < 0)
		return RC(rc, "%s", "fsl_uuid_to_rid");

	tree_view = view_open(0, 0, 0, start_col, FNC_VIEW_TREE);
	if (tree_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_tree_view(tree_view, "/", rid);
	if (!rc)
		*new_view = tree_view;
	return rc;
}

static void
branch_scroll_up(struct fnc_branch_view_state *s, int maxscroll)
{
	struct fnc_branchlist_entry	*be;
	int				 idx = 0;

	if (s->first_branch_onscreen == TAILQ_FIRST(&s->branches))
		return;

	be = TAILQ_PREV(s->first_branch_onscreen, fnc_branchlist_head, entries);
	while (idx++ < maxscroll) {
		if (be == NULL)
			break;
		s->first_branch_onscreen = be;
		be = TAILQ_PREV(be, fnc_branchlist_head, entries);
	}
}

static void
branch_scroll_down(struct fnc_branch_view_state *s, int maxscroll)
{
	struct fnc_branchlist_entry	*next, *last;
	int				 idx = 0;

	if (s->first_branch_onscreen)
		next = TAILQ_NEXT(s->first_branch_onscreen, entries);
	else
		next = TAILQ_FIRST(&s->branches);

	last = s->last_branch_onscreen;
	while (next && last && idx++ < maxscroll) {
		last = TAILQ_NEXT(last, entries);
		if (last) {
			s->first_branch_onscreen = next;
			next = TAILQ_NEXT(next, entries);
		}
	}
}

static int
branch_search_init(struct fnc_view *view)
{
	struct fnc_branch_view_state *s = &view->state.branch;

	s->matched_branch = NULL;
	return 0;
}

static int
branch_search_next(struct fnc_view *view)
{
	struct fnc_branch_view_state	*s = &view->state.branch;
	struct fnc_branchlist_entry	*be = NULL;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
		return 0;
	}

	if (s->matched_branch) {
		if (view->searching == SEARCH_FORWARD) {
			if (s->selected_branch)
				be = TAILQ_NEXT(s->selected_branch, entries);
			else
				be = TAILQ_PREV(s->selected_branch,
				    fnc_branchlist_head, entries);
		} else {
			if (s->selected_branch == NULL)
				be = TAILQ_LAST(&s->branches,
				    fnc_branchlist_head);
			else
				be = TAILQ_PREV(s->selected_branch,
				    fnc_branchlist_head, entries);
		}
	} else {
		if (view->searching == SEARCH_FORWARD)
			be = TAILQ_FIRST(&s->branches);
		else
			be = TAILQ_LAST(&s->branches, fnc_branchlist_head);
	}

	while (1) {
		if (be == NULL) {
			if (s->matched_branch == NULL) {
				view->search_status = SEARCH_CONTINUE;
				return 0;
			}
			if (view->searching == SEARCH_FORWARD)
				be = TAILQ_FIRST(&s->branches);
			else
				be = TAILQ_LAST(&s->branches,
				    fnc_branchlist_head);
		}

		if (match_branchlist_entry(be, &view->regex)) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_branch = be;
			break;
		}

		if (view->searching == SEARCH_FORWARD)
			be = TAILQ_NEXT(be, entries);
		else
			be = TAILQ_PREV(be, fnc_branchlist_head, entries);
	}

	if (s->matched_branch) {
		s->first_branch_onscreen = s->matched_branch;
		s->selected = 0;
	}

	return 0;
}

static int
match_branchlist_entry(struct fnc_branchlist_entry *be, regex_t *regex)
{
	regmatch_t regmatch;

	return regexec(regex, be->branch->name, 1, &regmatch, 0) == 0;
}

static int
close_branch_view(struct fnc_view *view)
{
	struct fnc_branch_view_state *s = &view->state.branch;

	fnc_free_branches(s);

	return 0;
}

static void
fnc_free_branches(struct fnc_branch_view_state *s)
{
	struct fnc_branchlist_entry *be;

	while (!TAILQ_EMPTY(&s->branches)) {
		be = TAILQ_FIRST(&s->branches);
		TAILQ_REMOVE(&s->branches, be, entries);
		fnc_branch_close(be->branch);
		fsl_free(be);
	}
}

static void
fnc_branch_close(struct fnc_branch *branch)
{
	fsl_free(branch->name);
	fsl_free(branch->date);
	fsl_free(branch->id);
	fsl_free(branch);
}

/*
 * Assign path to **inserted->path, with optional ->data assignment, and insert
 * in lexicographically sorted order into the doubly-linked list rooted at
 * *pathlist. If path is not unique, return without adding a duplicate entry.
 */
static int
fnc_pathlist_insert(struct fnc_pathlist_entry **inserted,
    struct fnc_pathlist_head *pathlist, const char *path, void *data)
{
	struct fnc_pathlist_entry	*new, *pe;
	int				 rc = 0;

	if (inserted)
		*inserted = NULL;

	new = fsl_malloc(sizeof(*new));
	if (new == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	new->path = path;
	new->pathlen = fsl_strlen(path);
	new->data = data;

	/*
	 * Most likely, supplied paths will be sorted (e.g., fnc diff *.c), so
	 * post-order traversal will be more efficient when inserting entries.
	 */
	pe = TAILQ_LAST(pathlist, fnc_pathlist_head);
	while (pe) {
		int cmp = fnc_path_cmp(pe->path, new->path, pe->pathlen,
		    new->pathlen);
		if (cmp == 0) {
			fsl_free(new);  /* Duplicate path; don't insert. */
			return rc;
		} else if (cmp < 0) {
			TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
			if (inserted)
				*inserted = new;
			return rc;
		}
		pe = TAILQ_PREV(pe, fnc_pathlist_head, entry);
	}

	TAILQ_INSERT_HEAD(pathlist, new, entry);
	if (inserted)
		*inserted = new;
	return rc;
}

static int
fnc_path_cmp(const char *path1, const char *path2, size_t len1, size_t len2)
{
	size_t	minlen;
	size_t	idx = 0;

	/* Trim any leading path separators. */
	while (path1[0] == '/') {
		++path1;
		--len1;
	}
	while (path2[0] == '/') {
		++path2;
		--len2;
	}
	minlen = MIN(len1, len2);

	/* Skip common prefix. */
	while (idx < minlen && path1[idx] == path2[idx])
		++idx;

	/* Are path lengths exactly equal (exluding path separators)? */
	if (len1 == len2 && idx >= minlen)
		return 0;

	/* Trim any redundant trailing path seperators. */
	while (path1[idx] == '/' && path1[idx + 1] == '/')
		++path1;
	while (path2[idx] == '/' && path2[idx + 1] == '/')
		++path2;

	/* Ignore trailing path separators. */
	if (path1[idx] == '/' && path1[idx + 1] == '\0' && path2[idx] == '\0')
		return 0;
	if (path2[idx] == '/' && path2[idx + 1] == '\0' && path1[idx] == '\0')
		return 0;

	/* Order children in subdirectories directly after their parents. */
	if (path1[idx] == '/' && path2[idx] == '\0')
		return 1;
	if (path2[idx] == '/' && path1[idx] == '\0')
		return -1;
	if (path1[idx] == '/' && path2[idx] != '\0')
		return -1;
	if (path2[idx] == '/' && path1[idx] != '\0')
		return 1;

	/* Character immediately after the common prefix determines order. */
	return (unsigned char)path1[idx] < (unsigned char)path2[idx] ? -1 : 1;
}

static void
fnc_pathlist_free(struct fnc_pathlist_head *pathlist)
{
	struct fnc_pathlist_entry *pe;

	while ((pe = TAILQ_FIRST(pathlist)) != NULL) {
		TAILQ_REMOVE(pathlist, pe, entry);
		free(pe);
	}
}

static void
fnc_show_version(void)
{
	printf("%s %s\n", fcli_progname(), PRINT_VERSION);
}

static int
strtonumcheck(int *ret, const char *nstr, const int min, const int max)
{
	const char	*ptr;
	int		 n;

	ptr = NULL;
	errno = 0;

	n = strtonum(nstr, min, max, &ptr);
	if (errno == ERANGE)
		return RC(FSL_RC_RANGE, "<n> out of range: -n|--limit=%s [%s]",
		    nstr, ptr);
	else if (errno != 0 || errno == EINVAL)
		return RC(FSL_RC_MISUSE, "<n> not a number: -n|--limit=%s [%s]",
		    nstr, ptr);
	else if (ptr && *ptr != '\0')
		return RC(FSL_RC_MISUSE,
		    "invalid char in <n>: -n|--limit=%s [%s]", nstr, ptr);

	*ret = n;
	return 0;
}

/*
 * Attempt to parse string d, which must resemble either an ISO8601 formatted
 * date (e.g., 2021-10-10, 2020-01-01T10:10:10), disgregarding any trailing
 * garbage or space characters such that "2021-10-10x" or "2020-01-01 10:10:10"
 * will pass, or an _unambiguous_ DD/MM/YYYY or MM/DD/YYYY formatted date. Upon
 * success, use when to determine which time component to add to the date (i.e.,
 * 1 sec before or after midnight), and convert to an mtime suitable for
 * comparisons with repository mtime fields and assign to *ret. Upon failure,
 * the error state will be updated with an appropriate error message and code.
 */
static int
fnc_date_to_mtime(double *ret, const char *d, int when)
{
	struct tm	t = {0, 0, 0, 0, 0, 0};
	char		iso8601[ISO8601_TIMESTAMP];

	/* Fill the tm structure. */
	if (strptime(d, "%Y-%m-%d", &t) == NULL) {
		/* If not YYYY-MM-DD, try MM/DD/YYYY and DD/MM/YYYY. */
		if (strptime(d, "%D", &t) != NULL) {
			/* If MM/DD/YYYY, check if it could be DD/MM/YYYY too */
			if (strptime(d, "%d/%m/%Y", &t) != NULL)
				return RC(FSL_RC_AMBIGUOUS,
				    "ambiguous date [%s]", d);
		} else if (strptime(d, "%d/%m/%Y", &t) != NULL) {
			/* If DD/MM/YYYY, check if it could be MM/DD/YYYY too */
			if (strptime(d, "%D", &t) != NULL)
				return RC(FSL_RC_AMBIGUOUS,
				    "ambiguous date [%s]", d);
		} else
			return RC(FSL_RC_TYPE, "unable to parse date: %s", d);
	}

	/* Format tm into ISO8601 string then convert to mtime. */
	if (when > 0)	/* After date d. */
		strftime(iso8601, ISO8601_TIMESTAMP, "%FT23:59:59", &t);
	else		/* Before date d. */
		strftime(iso8601, ISO8601_TIMESTAMP, "%FT00:00:01", &t);
	if (!fsl_iso8601_to_julian(iso8601, ret))
		return RC(FSL_RC_ERROR, "fsl_iso8601_to_julian(%s)", iso8601);

	return 0;
}

static char *
fnc_strsep(char **ptr, const char *sep)
{
	char	*s, *token;

	if ((s = *ptr) == NULL)
		return NULL;

	if (*(token = s + strcspn(s, sep)) != '\0') {
		*token++ = '\0';
		*ptr = token;
	} else
		*ptr = NULL;

	return s;
}

#ifdef __linux__
static size_t
fnc_strlcat(char *restrict dst, const char *restrict src, size_t dstsz)
{
	size_t	offset;
	int	dstlen, srclen, idx = 0;

	offset = dstlen = fsl_strlen(dst);
	srclen = fsl_strlen(src);

	while ((*(dst + offset++) = *(src + idx++)) != '\0')
		if (offset == dstsz - 1)
			break;

	*(dst + offset) = '\0';

	return dstlen + srclen;
}

static size_t
fnc_strlcpy(char *restrict dst, const char *restrict src, size_t dstsz)
{
	size_t offset = 0;

	if (dstsz < 1)
		goto end;

	while ((*(dst + offset) = *(src + offset)) != '\0')
		if (++offset == dstsz) {
			--offset;
			break;
		}

end:
	*(dst + offset) = '\0';
	while (*(src + offset) != '\0')
		++offset;	/* Return src length. */

	return offset;
}
#endif

Added lib/libfossil-config.h.















































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#if !defined(_NET_FOSSIL_SCM_FSL_AMALGAMATION_CONFIG_H_INCLUDED_)
#define _NET_FOSSIL_SCM_FSL_AMALGAMATION_CONFIG_H_INCLUDED_ 1
#define FSL_AUX_SCHEMA "2015-01-24"
#define FSL_CONTENT_SCHEMA "2"
#define FSL_PACKAGE_NAME "libfossil"
#define FSL_LIBRARY_VERSION "0.0.1-alphabeta"
/* Tweak the following for your system... */
#if !defined(HAVE_COMPRESS)
#  define HAVE_COMPRESS 1
#endif
#if !defined(HAVE_DLFCN_H)
#  define HAVE_DLFCN_H 0
#endif
#if !defined(HAVE_DLOPEN)
#  define HAVE_DLOPEN 0
#endif
#if !defined(HAVE_GETADDRINFO)
#  define HAVE_GETADDRINFO 0
#endif
#if !defined(HAVE_INET_NTOP)
#  define HAVE_INET_NTOP 0
#endif
#if !defined(HAVE_INTTYPES_H)
#  define HAVE_INTTYPES_H 0
#endif
#if !defined(HAVE_LIBDL)
#  define HAVE_LIBDL 0
#endif
#if !defined(HAVE_LIBLTDL)
#  define HAVE_LIBLTDL 0
#endif
#if !defined(_WIN32)
#if !defined(HAVE_LSTAT)
#  define HAVE_LSTAT 1
#endif
#if !defined(HAVE_LTDL_H)
#  define HAVE_LTDL_H 0
#endif
#if !defined(HAVE_LT_DLOPEN)
#  define HAVE_LT_DLOPEN 0
#endif
#if !defined(HAVE_OPENDIR)
#  define HAVE_OPENDIR 1
#endif
#if !defined(HAVE_PIPE)
#  define HAVE_PIPE 1
#endif
#if !defined(HAVE_STAT)
#  define HAVE_STAT 1
#endif
#if !defined(HAVE_STDINT_H)
#  define HAVE_STDINT_H 1
#endif
#if !defined(_DEFAULT_SOURCE)
#  define _DEFAULT_SOURCE 1
#endif
#if !defined(_XOPEN_SOURCE)
#  define _XOPEN_SOURCE 500
#endif
#else
#if !defined(HAVE_LSTAT)
#  define HAVE_LSTAT 0
#endif
#if !defined(HAVE_LTDL_H)
#  define HAVE_LTDL_H 0
#endif
#if !defined(HAVE_LT_DLOPEN)
#  define HAVE_LT_DLOPEN 0
#endif
#if !defined(HAVE_OPENDIR)
#  define HAVE_OPENDIR 1
#endif
#if !defined(HAVE_PIPE)
#  define HAVE_PIPE 0
#endif
#if !defined(HAVE_STAT)
#  define HAVE_STAT 0
#endif
#if !defined(HAVE_STDINT_H)
#  define HAVE_STDINT_H 1
#endif
#endif
/* _WIN32 */


#define FSL_LIB_VERSION_HASH "acbd39275f0d573a74d996caea7918afafff2ff7"
#define FSL_LIB_VERSION_TIMESTAMP "2021-10-08 03:15:51.855 UTC"
#define FSL_LIB_CONFIG_TIME "2021-10-08 04:07 GMT"
#if defined(_MSC_VER)
#define FSL_PLATFORM_OS "windows"
#define FSL_PLATFORM_IS_WINDOWS 1
#define FSL_PLATFORM_IS_UNIX 0
#define FSL_PLATFORM_PLATFORM "windows"
#define FSL_PLATFORM_PATH_SEPARATOR ";"
#define FSL_CHECKOUTDB_NAME "./_FOSSIL_"
/* define a __func__ compatibility macro */
#if _MSC_VER < 1500    /* (vc9.0; dev studio 2008) */
/* sorry; cant do much better than nothing at all on those earlier ones */
#define __func__ "(func)"
#else
#define __func__ __FUNCTION__
#endif
/* for the time being at least, don't complain about there being secure crt alternatives: */
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
/* for the time being at least, don't complain about using POSIX names instead of ISO C++: */
#pragma warning ( disable : 4996 )
/* for the time being at least, suppresss some int conversion warnings */
#pragma warning ( disable : 4244 )     /*'fsl_size_t' to 'int'; this masks other problems that should be fixed*/
#pragma warning ( disable : 4761 )     /*'integral size mismatch in argument'; more size_t problems*/
#pragma warning ( disable : 4267 )     /*'size_t' to 'int'; crops up especially in 64-bit builds*/
/* these were extracted from fossil's unistd.h */
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#include <io.h>
#elif defined(__MINGW32__)
#define FSL_PLATFORM_OS "mingw"
#define FSL_PLATFORM_IS_WINDOWS 1
#define FSL_PLATFORM_IS_UNIX 0
#define FSL_PLATFORM_PLATFORM "windows"
#define FSL_PLATFORM_PATH_SEPARATOR ";"
#define FSL_CHECKOUTDB_NAME "./.fslckout"
#elif defined(__CYGWIN__)
#define FSL_PLATFORM_OS "cygwin"
#define FSL_PLATFORM_IS_WINDOWS 0
#define FSL_PLATFORM_IS_UNIX 1
#define FSL_PLATFORM_PLATFORM "unix"
#define FSL_PLATFORM_PATH_SEPARATOR ":"
#define FSL_CHECKOUTDB_NAME "./_FOSSIL_"
#else
#define FSL_PLATFORM_OS "unknown"
#define FSL_PLATFORM_IS_WINDOWS 0
#define FSL_PLATFORM_IS_UNIX 1
#define FSL_PLATFORM_PLATFORM "unix"
#define FSL_PLATFORM_PATH_SEPARATOR ":"
#define FSL_CHECKOUTDB_NAME "./.fslckout"
#endif


#endif
/* _NET_FOSSIL_SCM_FSL_AMALGAMATION_CONFIG_H_INCLUDED_ */

Added lib/libfossil.c.

more than 10,000 changes

Added lib/libfossil.h.

more than 10,000 changes

Added lib/sqlite3.c.

more than 10,000 changes

Added lib/sqlite3.h.

more than 10,000 changes

Added lib/sqlite3ext.h.
























































































































































































































































































































































































































































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
** 2006 June 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the SQLite interface for use by
** shared libraries that want to be imported as extensions into
** an SQLite instance.  Shared libraries that intend to be loaded
** as extensions by SQLite should #include this file instead of 
** sqlite3.h.
*/
#ifndef SQLITE3EXT_H
#define SQLITE3EXT_H
#include "sqlite3.h"

/*
** The following structure holds pointers to all of the SQLite API
** routines.
**
** WARNING:  In order to maintain backwards compatibility, add new
** interfaces to the end of this structure only.  If you insert new
** interfaces in the middle of this structure, then older different
** versions of SQLite will not be able to load each other's shared
** libraries!
*/
struct sqlite3_api_routines {
  void * (*aggregate_context)(sqlite3_context*,int nBytes);
  int  (*aggregate_count)(sqlite3_context*);
  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  int  (*bind_double)(sqlite3_stmt*,int,double);
  int  (*bind_int)(sqlite3_stmt*,int,int);
  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  int  (*bind_null)(sqlite3_stmt*,int);
  int  (*bind_parameter_count)(sqlite3_stmt*);
  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  int  (*busy_timeout)(sqlite3*,int ms);
  int  (*changes)(sqlite3*);
  int  (*close)(sqlite3*);
  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
                           int eTextRep,const char*));
  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
                             int eTextRep,const void*));
  const void * (*column_blob)(sqlite3_stmt*,int iCol);
  int  (*column_bytes)(sqlite3_stmt*,int iCol);
  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
  int  (*column_count)(sqlite3_stmt*pStmt);
  const char * (*column_database_name)(sqlite3_stmt*,int);
  const void * (*column_database_name16)(sqlite3_stmt*,int);
  const char * (*column_decltype)(sqlite3_stmt*,int i);
  const void * (*column_decltype16)(sqlite3_stmt*,int);
  double  (*column_double)(sqlite3_stmt*,int iCol);
  int  (*column_int)(sqlite3_stmt*,int iCol);
  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
  const char * (*column_name)(sqlite3_stmt*,int);
  const void * (*column_name16)(sqlite3_stmt*,int);
  const char * (*column_origin_name)(sqlite3_stmt*,int);
  const void * (*column_origin_name16)(sqlite3_stmt*,int);
  const char * (*column_table_name)(sqlite3_stmt*,int);
  const void * (*column_table_name16)(sqlite3_stmt*,int);
  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  const void * (*column_text16)(sqlite3_stmt*,int iCol);
  int  (*column_type)(sqlite3_stmt*,int iCol);
  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  int  (*complete)(const char*sql);
  int  (*complete16)(const void*sql);
  int  (*create_collation)(sqlite3*,const char*,int,void*,
                           int(*)(void*,int,const void*,int,const void*));
  int  (*create_collation16)(sqlite3*,const void*,int,void*,
                             int(*)(void*,int,const void*,int,const void*));
  int  (*create_function)(sqlite3*,const char*,int,int,void*,
                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
                          void (*xFinal)(sqlite3_context*));
  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
                            void (*xFinal)(sqlite3_context*));
  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  int  (*data_count)(sqlite3_stmt*pStmt);
  sqlite3 * (*db_handle)(sqlite3_stmt*);
  int (*declare_vtab)(sqlite3*,const char*);
  int  (*enable_shared_cache)(int);
  int  (*errcode)(sqlite3*db);
  const char * (*errmsg)(sqlite3*);
  const void * (*errmsg16)(sqlite3*);
  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  int  (*expired)(sqlite3_stmt*);
  int  (*finalize)(sqlite3_stmt*pStmt);
  void  (*free)(void*);
  void  (*free_table)(char**result);
  int  (*get_autocommit)(sqlite3*);
  void * (*get_auxdata)(sqlite3_context*,int);
  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  int  (*global_recover)(void);
  void  (*interruptx)(sqlite3*);
  sqlite_int64  (*last_insert_rowid)(sqlite3*);
  const char * (*libversion)(void);
  int  (*libversion_number)(void);
  void *(*malloc)(int);
  char * (*mprintf)(const char*,...);
  int  (*open)(const char*,sqlite3**);
  int  (*open16)(const void*,sqlite3**);
  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  void *(*realloc)(void*,int);
  int  (*reset)(sqlite3_stmt*pStmt);
  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_double)(sqlite3_context*,double);
  void  (*result_error)(sqlite3_context*,const char*,int);
  void  (*result_error16)(sqlite3_context*,const void*,int);
  void  (*result_int)(sqlite3_context*,int);
  void  (*result_int64)(sqlite3_context*,sqlite_int64);
  void  (*result_null)(sqlite3_context*);
  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_value)(sqlite3_context*,sqlite3_value*);
  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
                         const char*,const char*),void*);
  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  char * (*xsnprintf)(int,char*,const char*,...);
  int  (*step)(sqlite3_stmt*);
  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
                                char const**,char const**,int*,int*,int*);
  void  (*thread_cleanup)(void);
  int  (*total_changes)(sqlite3*);
  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
                                         sqlite_int64),void*);
  void * (*user_data)(sqlite3_context*);
  const void * (*value_blob)(sqlite3_value*);
  int  (*value_bytes)(sqlite3_value*);
  int  (*value_bytes16)(sqlite3_value*);
  double  (*value_double)(sqlite3_value*);
  int  (*value_int)(sqlite3_value*);
  sqlite_int64  (*value_int64)(sqlite3_value*);
  int  (*value_numeric_type)(sqlite3_value*);
  const unsigned char * (*value_text)(sqlite3_value*);
  const void * (*value_text16)(sqlite3_value*);
  const void * (*value_text16be)(sqlite3_value*);
  const void * (*value_text16le)(sqlite3_value*);
  int  (*value_type)(sqlite3_value*);
  char *(*vmprintf)(const char*,va_list);
  /* Added ??? */
  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  /* Added by 3.3.13 */
  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  int (*clear_bindings)(sqlite3_stmt*);
  /* Added by 3.4.1 */
  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
                          void (*xDestroy)(void *));
  /* Added by 3.5.0 */
  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  int (*blob_bytes)(sqlite3_blob*);
  int (*blob_close)(sqlite3_blob*);
  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
                   int,sqlite3_blob**);
  int (*blob_read)(sqlite3_blob*,void*,int,int);
  int (*blob_write)(sqlite3_blob*,const void*,int,int);
  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
                             int(*)(void*,int,const void*,int,const void*),
                             void(*)(void*));
  int (*file_control)(sqlite3*,const char*,int,void*);
  sqlite3_int64 (*memory_highwater)(int);
  sqlite3_int64 (*memory_used)(void);
  sqlite3_mutex *(*mutex_alloc)(int);
  void (*mutex_enter)(sqlite3_mutex*);
  void (*mutex_free)(sqlite3_mutex*);
  void (*mutex_leave)(sqlite3_mutex*);
  int (*mutex_try)(sqlite3_mutex*);
  int (*open_v2)(const char*,sqlite3**,int,const char*);
  int (*release_memory)(int);
  void (*result_error_nomem)(sqlite3_context*);
  void (*result_error_toobig)(sqlite3_context*);
  int (*sleep)(int);
  void (*soft_heap_limit)(int);
  sqlite3_vfs *(*vfs_find)(const char*);
  int (*vfs_register)(sqlite3_vfs*,int);
  int (*vfs_unregister)(sqlite3_vfs*);
  int (*xthreadsafe)(void);
  void (*result_zeroblob)(sqlite3_context*,int);
  void (*result_error_code)(sqlite3_context*,int);
  int (*test_control)(int, ...);
  void (*randomness)(int,void*);
  sqlite3 *(*context_db_handle)(sqlite3_context*);
  int (*extended_result_codes)(sqlite3*,int);
  int (*limit)(sqlite3*,int,int);
  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  const char *(*sql)(sqlite3_stmt*);
  int (*status)(int,int*,int*,int);
  int (*backup_finish)(sqlite3_backup*);
  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  int (*backup_pagecount)(sqlite3_backup*);
  int (*backup_remaining)(sqlite3_backup*);
  int (*backup_step)(sqlite3_backup*,int);
  const char *(*compileoption_get)(int);
  int (*compileoption_used)(const char*);
  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
                            void (*xFinal)(sqlite3_context*),
                            void(*xDestroy)(void*));
  int (*db_config)(sqlite3*,int,...);
  sqlite3_mutex *(*db_mutex)(sqlite3*);
  int (*db_status)(sqlite3*,int,int*,int*,int);
  int (*extended_errcode)(sqlite3*);
  void (*log)(int,const char*,...);
  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  const char *(*sourceid)(void);
  int (*stmt_status)(sqlite3_stmt*,int,int);
  int (*strnicmp)(const char*,const char*,int);
  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  int (*wal_autocheckpoint)(sqlite3*,int);
  int (*wal_checkpoint)(sqlite3*,const char*);
  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  int (*vtab_config)(sqlite3*,int op,...);
  int (*vtab_on_conflict)(sqlite3*);
  /* Version 3.7.16 and later */
  int (*close_v2)(sqlite3*);
  const char *(*db_filename)(sqlite3*,const char*);
  int (*db_readonly)(sqlite3*,const char*);
  int (*db_release_memory)(sqlite3*);
  const char *(*errstr)(int);
  int (*stmt_busy)(sqlite3_stmt*);
  int (*stmt_readonly)(sqlite3_stmt*);
  int (*stricmp)(const char*,const char*);
  int (*uri_boolean)(const char*,const char*,int);
  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  const char *(*uri_parameter)(const char*,const char*);
  char *(*xvsnprintf)(int,char*,const char*,va_list);
  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  /* Version 3.8.7 and later */
  int (*auto_extension)(void(*)(void));
  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
                     void(*)(void*));
  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
                      void(*)(void*),unsigned char);
  int (*cancel_auto_extension)(void(*)(void));
  int (*load_extension)(sqlite3*,const char*,const char*,char**);
  void *(*malloc64)(sqlite3_uint64);
  sqlite3_uint64 (*msize)(void*);
  void *(*realloc64)(void*,sqlite3_uint64);
  void (*reset_auto_extension)(void);
  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
                        void(*)(void*));
  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
                         void(*)(void*), unsigned char);
  int (*strglob)(const char*,const char*);
  /* Version 3.8.11 and later */
  sqlite3_value *(*value_dup)(const sqlite3_value*);
  void (*value_free)(sqlite3_value*);
  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  /* Version 3.9.0 and later */
  unsigned int (*value_subtype)(sqlite3_value*);
  void (*result_subtype)(sqlite3_context*,unsigned int);
  /* Version 3.10.0 and later */
  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  int (*strlike)(const char*,const char*,unsigned int);
  int (*db_cacheflush)(sqlite3*);
  /* Version 3.12.0 and later */
  int (*system_errno)(sqlite3*);
  /* Version 3.14.0 and later */
  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  char *(*expanded_sql)(sqlite3_stmt*);
  /* Version 3.18.0 and later */
  void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  /* Version 3.20.0 and later */
  int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
                    sqlite3_stmt**,const char**);
  int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
                      sqlite3_stmt**,const void**);
  int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
  void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
  void *(*value_pointer)(sqlite3_value*,const char*);
  int (*vtab_nochange)(sqlite3_context*);
  int (*value_nochange)(sqlite3_value*);
  const char *(*vtab_collation)(sqlite3_index_info*,int);
  /* Version 3.24.0 and later */
  int (*keyword_count)(void);
  int (*keyword_name)(int,const char**,int*);
  int (*keyword_check)(const char*,int);
  sqlite3_str *(*str_new)(sqlite3*);
  char *(*str_finish)(sqlite3_str*);
  void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
  void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
  void (*str_append)(sqlite3_str*, const char *zIn, int N);
  void (*str_appendall)(sqlite3_str*, const char *zIn);
  void (*str_appendchar)(sqlite3_str*, int N, char C);
  void (*str_reset)(sqlite3_str*);
  int (*str_errcode)(sqlite3_str*);
  int (*str_length)(sqlite3_str*);
  char *(*str_value)(sqlite3_str*);
  /* Version 3.25.0 and later */
  int (*create_window_function)(sqlite3*,const char*,int,int,void*,
                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
                            void (*xFinal)(sqlite3_context*),
                            void (*xValue)(sqlite3_context*),
                            void (*xInv)(sqlite3_context*,int,sqlite3_value**),
                            void(*xDestroy)(void*));
  /* Version 3.26.0 and later */
  const char *(*normalized_sql)(sqlite3_stmt*);
  /* Version 3.28.0 and later */
  int (*stmt_isexplain)(sqlite3_stmt*);
  int (*value_frombind)(sqlite3_value*);
  /* Version 3.30.0 and later */
  int (*drop_modules)(sqlite3*,const char**);
  /* Version 3.31.0 and later */
  sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);
  const char *(*uri_key)(const char*,int);
  const char *(*filename_database)(const char*);
  const char *(*filename_journal)(const char*);
  const char *(*filename_wal)(const char*);
  /* Version 3.32.0 and later */
  char *(*create_filename)(const char*,const char*,const char*,
                           int,const char**);
  void (*free_filename)(char*);
  sqlite3_file *(*database_file_object)(const char*);
  /* Version 3.34.0 and later */
  int (*txn_state)(sqlite3*,const char*);
};

/*
** This is the function signature used for all extension entry points.  It
** is also defined in the file "loadext.c".
*/
typedef int (*sqlite3_loadext_entry)(
  sqlite3 *db,                       /* Handle to the database. */
  char **pzErrMsg,                   /* Used to set error string on failure. */
  const sqlite3_api_routines *pThunk /* Extension API function pointers. */
);

/*
** The following macros redefine the API routines so that they are
** redirected through the global sqlite3_api structure.
**
** This header file is also used by the loadext.c source file
** (part of the main SQLite library - not an extension) so that
** it can get access to the sqlite3_api_routines structure
** definition.  But the main library does not want to redefine
** the API.  So the redefinition macros are only valid if the
** SQLITE_CORE macros is undefined.
*/
#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
#endif
#define sqlite3_bind_blob              sqlite3_api->bind_blob
#define sqlite3_bind_double            sqlite3_api->bind_double
#define sqlite3_bind_int               sqlite3_api->bind_int
#define sqlite3_bind_int64             sqlite3_api->bind_int64
#define sqlite3_bind_null              sqlite3_api->bind_null
#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
#define sqlite3_bind_text              sqlite3_api->bind_text
#define sqlite3_bind_text16            sqlite3_api->bind_text16
#define sqlite3_bind_value             sqlite3_api->bind_value
#define sqlite3_busy_handler           sqlite3_api->busy_handler
#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
#define sqlite3_changes                sqlite3_api->changes
#define sqlite3_close                  sqlite3_api->close
#define sqlite3_collation_needed       sqlite3_api->collation_needed
#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
#define sqlite3_column_blob            sqlite3_api->column_blob
#define sqlite3_column_bytes           sqlite3_api->column_bytes
#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
#define sqlite3_column_count           sqlite3_api->column_count
#define sqlite3_column_database_name   sqlite3_api->column_database_name
#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
#define sqlite3_column_decltype        sqlite3_api->column_decltype
#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
#define sqlite3_column_double          sqlite3_api->column_double
#define sqlite3_column_int             sqlite3_api->column_int
#define sqlite3_column_int64           sqlite3_api->column_int64
#define sqlite3_column_name            sqlite3_api->column_name
#define sqlite3_column_name16          sqlite3_api->column_name16
#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
#define sqlite3_column_table_name      sqlite3_api->column_table_name
#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
#define sqlite3_column_text            sqlite3_api->column_text
#define sqlite3_column_text16          sqlite3_api->column_text16
#define sqlite3_column_type            sqlite3_api->column_type
#define sqlite3_column_value           sqlite3_api->column_value
#define sqlite3_commit_hook            sqlite3_api->commit_hook
#define sqlite3_complete               sqlite3_api->complete
#define sqlite3_complete16             sqlite3_api->complete16
#define sqlite3_create_collation       sqlite3_api->create_collation
#define sqlite3_create_collation16     sqlite3_api->create_collation16
#define sqlite3_create_function        sqlite3_api->create_function
#define sqlite3_create_function16      sqlite3_api->create_function16
#define sqlite3_create_module          sqlite3_api->create_module
#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
#define sqlite3_data_count             sqlite3_api->data_count
#define sqlite3_db_handle              sqlite3_api->db_handle
#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
#define sqlite3_errcode                sqlite3_api->errcode
#define sqlite3_errmsg                 sqlite3_api->errmsg
#define sqlite3_errmsg16               sqlite3_api->errmsg16
#define sqlite3_exec                   sqlite3_api->exec
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_expired                sqlite3_api->expired
#endif
#define sqlite3_finalize               sqlite3_api->finalize
#define sqlite3_free                   sqlite3_api->free
#define sqlite3_free_table             sqlite3_api->free_table
#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
#define sqlite3_get_table              sqlite3_api->get_table
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_global_recover         sqlite3_api->global_recover
#endif
#define sqlite3_interrupt              sqlite3_api->interruptx
#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
#define sqlite3_libversion             sqlite3_api->libversion
#define sqlite3_libversion_number      sqlite3_api->libversion_number
#define sqlite3_malloc                 sqlite3_api->malloc
#define sqlite3_mprintf                sqlite3_api->mprintf
#define sqlite3_open                   sqlite3_api->open
#define sqlite3_open16                 sqlite3_api->open16
#define sqlite3_prepare                sqlite3_api->prepare
#define sqlite3_prepare16              sqlite3_api->prepare16
#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
#define sqlite3_profile                sqlite3_api->profile
#define sqlite3_progress_handler       sqlite3_api->progress_handler
#define sqlite3_realloc                sqlite3_api->realloc
#define sqlite3_reset                  sqlite3_api->reset
#define sqlite3_result_blob            sqlite3_api->result_blob
#define sqlite3_result_double          sqlite3_api->result_double
#define sqlite3_result_error           sqlite3_api->result_error
#define sqlite3_result_error16         sqlite3_api->result_error16
#define sqlite3_result_int             sqlite3_api->result_int
#define sqlite3_result_int64           sqlite3_api->result_int64
#define sqlite3_result_null            sqlite3_api->result_null
#define sqlite3_result_text            sqlite3_api->result_text
#define sqlite3_result_text16          sqlite3_api->result_text16
#define sqlite3_result_text16be        sqlite3_api->result_text16be
#define sqlite3_result_text16le        sqlite3_api->result_text16le
#define sqlite3_result_value           sqlite3_api->result_value
#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
#define sqlite3_snprintf               sqlite3_api->xsnprintf
#define sqlite3_step                   sqlite3_api->step
#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
#define sqlite3_total_changes          sqlite3_api->total_changes
#define sqlite3_trace                  sqlite3_api->trace
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
#endif
#define sqlite3_update_hook            sqlite3_api->update_hook
#define sqlite3_user_data              sqlite3_api->user_data
#define sqlite3_value_blob             sqlite3_api->value_blob
#define sqlite3_value_bytes            sqlite3_api->value_bytes
#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
#define sqlite3_value_double           sqlite3_api->value_double
#define sqlite3_value_int              sqlite3_api->value_int
#define sqlite3_value_int64            sqlite3_api->value_int64
#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
#define sqlite3_value_text             sqlite3_api->value_text
#define sqlite3_value_text16           sqlite3_api->value_text16
#define sqlite3_value_text16be         sqlite3_api->value_text16be
#define sqlite3_value_text16le         sqlite3_api->value_text16le
#define sqlite3_value_type             sqlite3_api->value_type
#define sqlite3_vmprintf               sqlite3_api->vmprintf
#define sqlite3_vsnprintf              sqlite3_api->xvsnprintf
#define sqlite3_overload_function      sqlite3_api->overload_function
#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
#define sqlite3_blob_close             sqlite3_api->blob_close
#define sqlite3_blob_open              sqlite3_api->blob_open
#define sqlite3_blob_read              sqlite3_api->blob_read
#define sqlite3_blob_write             sqlite3_api->blob_write
#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
#define sqlite3_file_control           sqlite3_api->file_control
#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
#define sqlite3_memory_used            sqlite3_api->memory_used
#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
#define sqlite3_mutex_free             sqlite3_api->mutex_free
#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
#define sqlite3_mutex_try              sqlite3_api->mutex_try
#define sqlite3_open_v2                sqlite3_api->open_v2
#define sqlite3_release_memory         sqlite3_api->release_memory
#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
#define sqlite3_sleep                  sqlite3_api->sleep
#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
#define sqlite3_vfs_find               sqlite3_api->vfs_find
#define sqlite3_vfs_register           sqlite3_api->vfs_register
#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
#define sqlite3_result_error_code      sqlite3_api->result_error_code
#define sqlite3_test_control           sqlite3_api->test_control
#define sqlite3_randomness             sqlite3_api->randomness
#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
#define sqlite3_limit                  sqlite3_api->limit
#define sqlite3_next_stmt              sqlite3_api->next_stmt
#define sqlite3_sql                    sqlite3_api->sql
#define sqlite3_status                 sqlite3_api->status
#define sqlite3_backup_finish          sqlite3_api->backup_finish
#define sqlite3_backup_init            sqlite3_api->backup_init
#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
#define sqlite3_backup_step            sqlite3_api->backup_step
#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
#define sqlite3_db_config              sqlite3_api->db_config
#define sqlite3_db_mutex               sqlite3_api->db_mutex
#define sqlite3_db_status              sqlite3_api->db_status
#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
#define sqlite3_log                    sqlite3_api->log
#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
#define sqlite3_sourceid               sqlite3_api->sourceid
#define sqlite3_stmt_status            sqlite3_api->stmt_status
#define sqlite3_strnicmp               sqlite3_api->strnicmp
#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
#define sqlite3_wal_hook               sqlite3_api->wal_hook
#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
#define sqlite3_vtab_config            sqlite3_api->vtab_config
#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
/* Version 3.7.16 and later */
#define sqlite3_close_v2               sqlite3_api->close_v2
#define sqlite3_db_filename            sqlite3_api->db_filename
#define sqlite3_db_readonly            sqlite3_api->db_readonly
#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
#define sqlite3_errstr                 sqlite3_api->errstr
#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
#define sqlite3_stricmp                sqlite3_api->stricmp
#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
#define sqlite3_uri_int64              sqlite3_api->uri_int64
#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
#define sqlite3_uri_vsnprintf          sqlite3_api->xvsnprintf
#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
/* Version 3.8.7 and later */
#define sqlite3_auto_extension         sqlite3_api->auto_extension
#define sqlite3_bind_blob64            sqlite3_api->bind_blob64
#define sqlite3_bind_text64            sqlite3_api->bind_text64
#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
#define sqlite3_load_extension         sqlite3_api->load_extension
#define sqlite3_malloc64               sqlite3_api->malloc64
#define sqlite3_msize                  sqlite3_api->msize
#define sqlite3_realloc64              sqlite3_api->realloc64
#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
#define sqlite3_result_blob64          sqlite3_api->result_blob64
#define sqlite3_result_text64          sqlite3_api->result_text64
#define sqlite3_strglob                sqlite3_api->strglob
/* Version 3.8.11 and later */
#define sqlite3_value_dup              sqlite3_api->value_dup
#define sqlite3_value_free             sqlite3_api->value_free
#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
/* Version 3.9.0 and later */
#define sqlite3_value_subtype          sqlite3_api->value_subtype
#define sqlite3_result_subtype         sqlite3_api->result_subtype
/* Version 3.10.0 and later */
#define sqlite3_status64               sqlite3_api->status64
#define sqlite3_strlike                sqlite3_api->strlike
#define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
/* Version 3.12.0 and later */
#define sqlite3_system_errno           sqlite3_api->system_errno
/* Version 3.14.0 and later */
#define sqlite3_trace_v2               sqlite3_api->trace_v2
#define sqlite3_expanded_sql           sqlite3_api->expanded_sql
/* Version 3.18.0 and later */
#define sqlite3_set_last_insert_rowid  sqlite3_api->set_last_insert_rowid
/* Version 3.20.0 and later */
#define sqlite3_prepare_v3             sqlite3_api->prepare_v3
#define sqlite3_prepare16_v3           sqlite3_api->prepare16_v3
#define sqlite3_bind_pointer           sqlite3_api->bind_pointer
#define sqlite3_result_pointer         sqlite3_api->result_pointer
#define sqlite3_value_pointer          sqlite3_api->value_pointer
/* Version 3.22.0 and later */
#define sqlite3_vtab_nochange          sqlite3_api->vtab_nochange
#define sqlite3_value_nochange         sqlite3_api->value_nochange
#define sqlite3_vtab_collation         sqlite3_api->vtab_collation
/* Version 3.24.0 and later */
#define sqlite3_keyword_count          sqlite3_api->keyword_count
#define sqlite3_keyword_name           sqlite3_api->keyword_name
#define sqlite3_keyword_check          sqlite3_api->keyword_check
#define sqlite3_str_new                sqlite3_api->str_new
#define sqlite3_str_finish             sqlite3_api->str_finish
#define sqlite3_str_appendf            sqlite3_api->str_appendf
#define sqlite3_str_vappendf           sqlite3_api->str_vappendf
#define sqlite3_str_append             sqlite3_api->str_append
#define sqlite3_str_appendall          sqlite3_api->str_appendall
#define sqlite3_str_appendchar         sqlite3_api->str_appendchar
#define sqlite3_str_reset              sqlite3_api->str_reset
#define sqlite3_str_errcode            sqlite3_api->str_errcode
#define sqlite3_str_length             sqlite3_api->str_length
#define sqlite3_str_value              sqlite3_api->str_value
/* Version 3.25.0 and later */
#define sqlite3_create_window_function sqlite3_api->create_window_function
/* Version 3.26.0 and later */
#define sqlite3_normalized_sql         sqlite3_api->normalized_sql
/* Version 3.28.0 and later */
#define sqlite3_stmt_isexplain         sqlite3_api->stmt_isexplain
#define sqlite3_value_frombind         sqlite3_api->value_frombind
/* Version 3.30.0 and later */
#define sqlite3_drop_modules           sqlite3_api->drop_modules
/* Version 3.31.0 and later */
#define sqlite3_hard_heap_limit64      sqlite3_api->hard_heap_limit64
#define sqlite3_uri_key                sqlite3_api->uri_key
#define sqlite3_filename_database      sqlite3_api->filename_database
#define sqlite3_filename_journal       sqlite3_api->filename_journal
#define sqlite3_filename_wal           sqlite3_api->filename_wal
/* Version 3.32.0 and later */
#define sqlite3_create_filename        sqlite3_api->create_filename
#define sqlite3_free_filename          sqlite3_api->free_filename
#define sqlite3_database_file_object   sqlite3_api->database_file_object
/* Version 3.34.0 and later */
#define sqlite3_txn_state              sqlite3_api->txn_state
#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */

#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  /* This case when the file really is being compiled as a loadable 
  ** extension */
# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
# define SQLITE_EXTENSION_INIT3     \
    extern const sqlite3_api_routines *sqlite3_api;
#else
  /* This case when the file is being statically linked into the 
  ** application */
# define SQLITE_EXTENSION_INIT1     /*no-op*/
# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
# define SQLITE_EXTENSION_INIT3     /*no-op*/
#endif

#endif /* SQLITE3EXT_H */

Deleted shakenmake.make.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525













































































































































































































































































































































































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
########################################################################
# ShakeNMake is a GNU Makefile mini-framework for small C/C++ source
# trees (with a small handful of directories, building libraries
# and/or applications. It relies very much on GNU Make 3.81+ and its
# dependencies generation relies on GCC (for the preprocessor only),
# even if GCC will not be used be used as the primary compiler.
all:
########################################################################
# Maintainer's/hacker's notes:
#
# Vars names starting with ShakeNMake are mostly internal to this
# makefile and are considered "private" unless documented otherwise.
# Notable exceptions are most of the ShakeNMake.CALL entries, which
# are $(call)able functions, and ShakeNMake.EVAL entries, which are
# $(eval)able code.
#
########################################################################


########################################################################
# Calculate the top of the source tree, in case this is included
# from a subdir.
ShakeNMake.MAKEFILE := $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
$(ShakeNMake.MAKEFILE):# avoid breaking some deps checks if someone renames this file (been there, done that)
TOP_SRCDIR_REL ?= $(patsubst %/,%,$(dir $(ShakeNMake.MAKEFILE)))
#TOP_SRCDIR := $(shell cd -P $(TOP_SRCDIR_REL) && pwd)
TOP_SRCDIR := $(realpath $(TOP_SRCDIR_REL))
#$(error TOP_SRCDIR_REL=$(TOP_SRCDIR_REL)   TOP_SRCDIR=$(TOP_SRCDIR))
#TOP_INCDIR := $(TOP_SRCDIR_REL)/include
#TOP_INCDIR := $(TOP_SRCDIR)/include
#INCLUDES += -I. -I$(TOP_INCDIR) -I$(HOME)/include
#CPPFLAGS += $(INCLUDES)

#TOP_DIR ?= .#$(PWD)
#ShakeNMake.CISH_SOURCES += $(wildcard *.c)

PACKAGE.MAKEFILE := $(firstword $(MAKEFILE_LIST))# normally either Makefile or GNUmakefile
$(PACKAGE.MAKEFILE):


########################################################################
# ShakeNMake.CALL.FIND_FILE call()able function:
# $1 = app name
# $2 = optional path ($(PATH) is always included)
ShakeNMake.CALL.FIND_FILE = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(2) $(PATH)))))
########################################################################
ShakeNMake.BIN.AR ?= $(call ShakeNMake.CALL.FIND_FILE,$(AR))
ShakeNMake.BIN.GCC ?= $(call ShakeNMake.CALL.FIND_FILE,gcc)
ShakeNMake.BIN.INSTALL ?= $(call ShakeNMake.CALL.FIND_FILE,install)

ifneq (,$(COMSPEC))
$(warning Setting ShakeNMake.SMELLS.LIKE.WINDOWS to 1)
ShakeNMake.SMELLS.LIKE.WINDOWS := 1
ShakeNMake.EXTENSIONS.DLL = .dll
ShakeNMake.EXTENSIONS.LIB = .lib
ShakeNMake.EXTENSIONS.EXE = .exe
else
ShakeNMake.SMELLS.LIKE.WINDOWS := 0
ShakeNMake.EXTENSIONS.DLL = .so
ShakeNMake.EXTENSIONS.LIB = .a
ShakeNMake.EXTENSIONS.EXE =# no whitespace, please
endif

########################################################################
# Cleanup rules.
# To ensure proper cleanup order, define deps on clean-., like so:
# clean-.: clean-mysubdir
# clean-mysubdir: clean-prereqsubdir
#...
.PHONY: clean distclean clean-. distclean-.
clean-%:
	@$(MAKE) --no-print-directory -C $* clean
clean-.:
	@-echo "Cleaning up $(CURDIR)..."; \
	rm -f $@.$$$$ $(CLEAN_FILES) 

clean: clean-.

distclean-%:
	@$(MAKE) --no-print-directory -C $* distclean
distclean-.:
	@-echo "Dist-cleaning up $(CURDIR)..."; \
	rm -f $@.$$$$ $(CLEAN_FILES) $(DISTCLEAN_FILES) 
distclean: distclean-.


########################################################################
# An internal hack to enable "quiet" output. $(1) is a string which
# is shown ONLY if ShakeNMake.QUIET!=1
ShakeNMake.QUIET ?= 0
define ShakeNMake.CALL.SETX
if test x1 = "x$(ShakeNMake.QUIET)"; then echo $(1); else set -x; fi
endef
########################################################################

########################################################################
# Building a static library:
#
#   myLib.LIB.OBJECTS = foo.o bar.o
#   $(call ShakeNMake.CALL.RULES.LIBS,myLib)
#
# A target named myLib.LIB is created for building the library and
# $(myLib.LIB) holds the name of the compiled lib (typically
# "myLib.a").
#
########################################################################
# ShakeNMake.EVAL.RULES.LIB creates rules to build static library
# $(1).a
define ShakeNMake.EVAL.RULES.LIB
$(1).LIB = $(1).a
$(1).LIB: $$($(1).LIB)
CLEAN_FILES += $$($(1).LIB)
$$($(1).LIB): $$($(1).LIB.OBJECTS)
	@$(call ShakeNMake.CALL.SETX,"AR [$$@]"); \
		$$(ShakeNMake.BIN.AR) crs $$@ $$($(1).LIB.OBJECTS)
endef
define ShakeNMake.CALL.RULES.LIBS
$(foreach liba,$(1),$(eval $(call ShakeNMake.EVAL.RULES.LIB,$(liba))))
endef
# end ShakeNMake.EVAL.RULES.LIB
########################################################################

########################################################################
# ShakeNMake.EVAL.RULES.DLL builds builds
# $(1)$(ShakeNMake.EXTENSIONS.DLL) from object files defined by
# $(1).DLL.OBJECTS and $(1).DLL.SOURCES. Flags passed on to the shared
# library linker ($(CC)) include:
#
#   LDFLAGS, $(1).DLL.LDFLAGS, LDADD, -shared -static-libgcc,
#   $(1).DLL.OBJECTS, $(1).DLL.LDFLAGS
#
# Also defines the var $(1).DLL, which expands to the filename of the DLL,
# (normally $(1)$(ShakeNMake.EXTENSIONS.DLL)).
define ShakeNMake.EVAL.RULES.DLL
$(1).DLL = $(1)$(ShakeNMake.EXTENSIONS.DLL)
ifneq (.DLL,$(ShakeNMake.EXTENSIONS.DLL))
$(1).DLL: $$($(1).DLL)
endif
CLEAN_FILES += $$($(1).DLL)
$$($(1).DLL): $$($(1).DLL.SOURCES) $$($(1).DLL.OBJECTS)
	@test x = "x$$($(1).DLL.OBJECTS)$$($(1).DLL.SOURCES)" && { \
	echo "$(1).DLL.OBJECTS and/or $(1).DLL.SOURCES are/is undefined!"; exit 1; }; \
	$(call ShakeNMake.CALL.SETX,"LD [$$@]"); \
	 $$(CC) -o $$@ -shared $$(LDFLAGS) $(LDLIBS) \
		$$($(1).DLL.OBJECTS) \
		$$($(1).DLL.LDFLAGS)
endef
########################################################################
# $(call ShakeNMake.CALL.RULES.DLLS,[list]) calls and $(eval)s
# ShakeNMake.EVAL.RULES.DLL for each entry in $(1)
define ShakeNMake.CALL.RULES.DLLS
$(foreach dll,$(1),$(eval $(call ShakeNMake.EVAL.RULES.DLL,$(dll))))
endef
# end ShakeNMake.CALL.RULES.DLLS and friends
########################################################################


########################################################################
# ShakeNMake.CALL.RULES.BIN is intended to be called like so:
# $(eval $(call ShakeNMake.CALL.RULES.BIN,MyApp))
#
# It builds a binary named $(1) by running $(CXX) and passing it:
#
# LDFLAGS, $(1).BIN.LDFLAGS, $(1).BIN.OBJECTS
define ShakeNMake.CALL.RULES.BIN
$(1).BIN := $(1)$(ShakeNMake.EXTENSIONS.EXE)
$(1).BIN: $$($(1).BIN)
# Many developers feel that bins should not be cleaned by 'make
# clean', but instead by distclean, but i'm not one of those
# developers. i subscribe more to the school of thought that distclean
# is for cleaning up configure-created files. That said, shake-n-make
# isn't designed to use a configure-like process, so that is probably
# moot here and we probably (maybe?) should clean up bins only in
# distclean. As always: hack it to suit your preference:
CLEAN_FILES += $$($(1).BIN)
$$($(1).BIN): $$($(1).BIN.OBJECTS)
	@test x = "x$$($(1).BIN.OBJECTS)" && { \
	echo "$(1).BIN.OBJECTS is undefined!"; exit 1; }; \
	$(call ShakeNMake.CALL.SETX,"LINK [$$@]"); \
	$$(CC) -o $$@ \
		$$($(1).BIN.OBJECTS) \
		$$(LDFLAGS) $$($(1).BIN.LDFLAGS)
endef
########################################################################
# $(call ShakeNMake.EVAL.RULES.BINS,[list]) calls and $(eval)s
# ShakeNMake.CALL.RULES.BIN for each entry in $(1)
define ShakeNMake.CALL.RULES.BINS
$(foreach bin,$(1),$(eval $(call ShakeNMake.CALL.RULES.BIN,$(bin))))
endef
# end ShakeNMake.CALL.RULES.BIN and friends
########################################################################

########################################################################
# Sets up rules for subdir $1.
########################################################################
# Newer (2021-09-01) subdir rules, ported over from toc...
#
# $(call ShakeNMake.CALL.MAKE-SUBDIRS,dirs_list[,target_name=all])
# Walks each dir in $(1), calling $(MAKE) $(2) for each one.
#
#   $1 = list of dirs
#   $2 = make target
#
# Note that this approach makes parallel builds between the dirs in
# $(1) impossible, so it should only be used for targets where
# parallelizing stuff may screw things up or is otherwise not desired
# or not significant.
ShakeNMake.CALL.MAKE-SUBDIRS = \
	test "x$(1)" = "x" -o "x." = "x$(1)" && exit 0; \
	tgt="$(if $(2),$(2),all)"; \
	make_nop_arg=''; \
	test 1 = 1 -o x1 = "x$(ShakeNMake.QUIET)" && make_nop_arg="--no-print-directory"; \
	for b in $(1) "x"; do test ".x" = ".$$$$b" && break; \
		pwd=$$$$(pwd); \
		deep=0; while test $$$$deep -lt $(MAKELEVEL); do echo -n "  "; deep=$$$$((deep+1)); done; \
		echo "Making '$$$$tgt' in $$$${PWD}/$$$${b}"; \
		$(MAKE) -C $$$${b} $$$${make_nop_arg} $$$${tgt} || exit; \
		cd $$$$pwd || exit; \
	done
.PHONY: subdirs $(ShakeNMake.subdirs) $(patsubst %,subdir-%,$(ShakeNMake.subdirs))
$(ShakeNMake.subdirs):
	@+$(call ShakeNMake.MAKE-SUBDIRS,$@,all)
subdirs: $(ShakeNMake.subdirs)
subdir-%:# run all in subdir $*
	@+$(call ShakeNMake.MAKE-SUBDIRS,$*,all)
subdirs-%:# run target % in $(ShakeNMake.subdirs)
	@+$(call ShakeNMake.MAKE-SUBDIRS,$(ShakeNMake.subdirs),$*)
#########################################################################
.PHONY: subdir-.
subdir-.:
define ShakeNMake.CALL.SUBDIR
.PHONY: $(1)
subdir-$(1):
	@+$(call ShakeNMake.CALL.MAKE-SUBDIRS,$(1),all)
clean: clean-$(1)
clean-.: clean-$(1)
distclean-.: distclean-$(1)
subdir-install-$(1):
	@+$(call ShakeNMake.CALL.MAKE-SUBDIRS,$(1),install)
install: subdir-install-$(1)
subdir-uninstall-$(1):
	@+$(call ShakeNMake.CALL.MAKE-SUBDIRS,$(1),uninstall)
uninstall: subdir-uninstall-$(1)
ShakeNMake.subdirs += $(1)
endef
define ShakeNMake.CALL.SUBDIRS
$(foreach dir,$(1),$(eval $(call ShakeNMake.CALL.SUBDIR,$(dir))))
endef
# end ShakeNMake.CALL.SUBDIR and friends
########################################################################


########################################################################
# Automatic dependencies generation for C/C++ code...
# To disable deps generation, set ShakeNMake.USE_MKDEPS=0 *before*
# including this file.
ShakeNMake.USE_MKDEPS := 1
ifeq (,$(ShakeNMake.BIN.GCC))
ShakeNMake.USE_MKDEPS ?= 0
else
ShakeNMake.USE_MKDEPS ?= 1
endif
#$(warning ShakeNMake.USE_MKDEPS=$(ShakeNMake.USE_MKDEPS));
ifeq (1,$(ShakeNMake.USE_MKDEPS))
ShakeNMake.CISH_SOURCES ?= $(wildcard *.cpp *.c *.c++ *.h *.hpp *.h++ *.hh)
#$(warning ShakeNMake.CISH_SOURCES=$(ShakeNMake.CISH_SOURCES))

ifneq (,$(ShakeNMake.CISH_SOURCES))
ShakeNMake.CISH_DEPS_FILE := .make.c_deps
ShakeNMake.BIN.MKDEP = gcc -w -E -MM $(CPPFLAGS)
#$(ShakeNMake.CISH_SOURCES): $(filter-out $(ShakeNMake.CISH_DEPS_FILE),$(MAKEFILE_LIST))
CLEAN_FILES += $(ShakeNMake.CISH_DEPS_FILE)
$(ShakeNMake.CISH_DEPS_FILE): $(PACKAGE.MAKEFILE) $(ShakeNMake.MAKEFILE) $(ShakeNMake.CISH_SOURCES)
	@touch $@; test x = "x$(ShakeNMake.CISH_SOURCES)" && exit 0; \
	echo "Generating dependencies..."; \
	$(ShakeNMake.BIN.MKDEP) $(ShakeNMake.CISH_SOURCES) 2>/dev/null > $@ || exit

#	perl -i -pe 's|^(.+)\.o:\s*((\w+/)*)|$(OBJ.DIR)/$$1.o: $(filter-out $(ShakeNMake.CISH_DEPS_FILE),$(MAKEFILE_LIST))\n$(OBJ.DIR)/$$1.o: $$2|' $@
# That perl bit is a big, ugly, tree-specific hack for libfossil!
# gcc -E -MM strips directory parts (why, i cannot imagine), so we've got to
# hack the output.
# Example: input= src/Foo.cpp
# Generated deps:
#  Foo.o: src/Foo.cpp ...
# So we re-extract that first path and prepend it to Foo.o using the
# above perl.  We also add $(MAKEFILE_LIST) has a prereq of all src
# files because i belong to the school of tought which believes that
# changes to the arbitrary build options set in the makefiles should
# cause a rebuild.
#	if [[ x = "x$(TOP_DIR)" ]]; then echo "REMOVE THIS TREE-SPECIFIC HACK!"; exit 1; fi;\
#ifeq (,$(TOP_DIR))
#$(error Tree-specific hack in place here. See the comments and remove these lines or set TOP_DIR)
#endif
# normally we also want:
#  || $(ShakeNMake.BIN.RM) -f $@ 2>/dev/null
# because we don't want a bad generated makefile to kill the build, but gcc -E
# is returning 1 when some generated files do not yet exist.
deps: $(ShakeNMake.CISH_DEPS_FILE)

ifneq (,$(strip $(filter distclean clean,$(MAKECMDGOALS))))
# $(warning Skipping C/C++ deps generation.)
# ABSOLUTEBOGO := $(shell $(ShakeNMake.BIN.RM) -f $(ShakeNMake.CISH_DEPS_FILE))
else
#$(warning Including C/C++ deps.)
-include $(ShakeNMake.CISH_DEPS_FILE)
endif

endif
# ^^^^ ifneq(,$(ShakeNMake.CISH_SOURCES))
endif
# ^^^^ end $(ShakeNMake.USE_MKDEPS)
########################################################################

########################################################################
# Deps, Tromey's Way:
# $(call ShakeNBake.CALL.MkDep.Tromey,source-file,object-file,depend-file)
ifeq (0,1)
.dfiles.list = $(wildcard *.o.d) $(shell find src -name '*.o.d')
ifneq (,$(.dfiles.list))
# $(error include $(.dfiles.list))
include $(.dfiles.list)
endif

define ShakeNBake.CALL.MkDep.Tromey
$(ShakeNMake.BIN.GCC) -MM \
	-w	\
	-MF $(1).d         \
	-MP            \
	-MT $2         \
	$(CPPFLAGS)    \
	$(TARGET_ARCH) \
	$1
endef

CLEAN_FILES += $(wildcard *.o.d)
%.o: %.c $(mkdir_compdb)
	@$(call ShakeNMake.CALL.SETX,"CC [$@]"); \
	$(COMPILE.c) -MM -MF $(@).d -MP -MT $@.d $(COMPILE.c.OPTIONS) $(OUTPUT_OPTION) $<
#	$(call ShakeNBake.CALL.MkDep.Tromey,$<,$@,$(@).d);

%.o: %.cpp
	@$(call ShakeNMake.CALL.SETX,"C++ [$@]"); \
	$(COMPILE.cc) -MM -MF $@.d -MP -MT $@ $(COMPILE.cc.OPTIONS) $(OUTPUT_OPTION) $<
#	$(COMPILE.cc) $(COMPILE.cc.OPTIONS) $(OUTPUT_OPTION) $<
#	$(call ShakeNBake.CALL.MkDep.Tromey,$<,$@,$(@).d);
else
%.o: %.c $(mkdir_compdb)
	@$(call ShakeNMake.CALL.SETX,"CC [$@]"); \
	$(COMPILE.c) $(COMPILE.c.OPTIONS) $(OUTPUT_OPTION) $<

%.o: %.cpp
	@$(call ShakeNMake.CALL.SETX,"C++ [$@]"); \
	$(COMPILE.cc) $(COMPILE.cc.OPTIONS) $(OUTPUT_OPTION) $<
endif # Tromey's Way

########################################################################
# create emacs tags...
ifneq (1,$(ShakeNMake.ETAGS.DISABLE))
bin_etags := $(call ShakeNMake.CALL.FIND_FILE,etags)
ifeq (.,$(TOP_SRCDIR_REL))
ifneq (,$(bin_etags))
TAGTHESE := $(shell find . -name '*.[ch]' -print)
ifneq (,$(TAGTHESE))
    $(TAGTHESE):
    TAGFILE := TAGS
    $(TAGFILE): $(TAGTHESE) # $(MAKEFILE_LIST)
	@echo "Creating $@..."; \
	for x in $(TAGTHESE); do echo $$x; done | $(bin_etags) -f $@ -; \
		touch $@; true
# ^^^^ Martin G. reports that etags fails with "Unknown option: -" on his
# Ubuntun 18.04 system. Since this isn't a critical feature, we can just
# force this step to succeed.
    tags: $(TAGFILE)
    CLEAN_FILES += $(TAGFILE)
    all: $(TAGFILE)
endif
endif
# ^^^ bin_etags
endif
# ^^^ TOP_SRCDIR_REL==.
endif
# ^^^ $(ShakeNMake.TAGS.DISABLE)

#%.o:
#	@$$(call ShakeNMake.CALL.SETX,"CC [$@] ..."); \
#	$(COMPILE.c) $(COMPILE.c.OPTIONS) -o $@

########################################################################
# Installation rules...
#
# Sample usage:
#
#  ShakeNMake.install.bins = mybin myotherbin # installs to $(DESTDIR)$(prefix)/bin
#  ShakeNMake.install.libs = mylib.a myotherlib.a # installs to $(DESTDIR)$(prefix)/lib
#
# Where (bins, libs...) is the name of an installation rule set, the
# complete list of which is defined somewhere below.
#
# Then `make install` will try to DTRT with those.
#
# These rules are quite ancient - dating back to the very early 2000's
# - and arguably severely overengineered. As part of the port out of
# the original tree, the subdir handling "might" have been broken, so
# be on the lookout for that.
ifeq (,$(wildcard $(ShakeNMake.BIN.INSTALL)))
uninstall install:
	@echo "Install rules require that the variable ShakeNMake.BIN.INSTALL be set."; exit 1
else
DESTDIR ?=
prefix ?= /usr/local
########################################################################
# $(call ShakeNMake.CALL.INSTALL.grep_kludge,file_name)
# This is an ancient kludge force [un]install to silently fail without an
# error when passed an empty file list. This was done because saner
# approaches to checking this failed to work on some older machines.
ShakeNMake.CALL.INSTALL.grep_kludge = echo $(1) "" | grep -q '[a-zA-Z0-9]' || exit 0
########################################################################
# $(call ShakeNMake.CALL.INSTALL,file_list,destdir[,install-sh-flags])
# Installs files $(1) to $(DESTDIR)$(2). $(3) is passed on to
# $(ShakeNMake.BIN.INSTALL).
#
# This code has some rather old logic in it when uses 'cmp' to compare
# the source and dest files, and does not update the destination if
# they are the same. This was originally in place because the install
# code was used to copy header files around the source tree during
# build-time, and we wanted to avoid breaking dependencies. It hasn't
# been used in that way in a long, long time (2003? 2004?) and can
# probably be removed, as it just slows down the install process.
ShakeNMake.CALL.INSTALL = $(call ShakeNMake.CALL.INSTALL.grep_kludge,$(1)); \
	tgtdir="$(DESTDIR)$(2)"; \
	test -d "$$tgtdir" || mkdir -p "$${tgtdir}" \
		|| { err=$$?; echo "$(@): mkdir -p $${tgtdir} failed"; exit $$err; }; \
	for b in $(1) ""; do test -z "$$b" && continue; \
		b=$${b\#\#*/}; \
		target="$${tgtdir}/$$b"; \
		cmd="$(ShakeNMake.BIN.INSTALL) $(3) $$b $$target"; echo $$cmd; $$cmd || exit; \
	done

########################################################################
# $(call ShakeNMake.CALL.UNINSTALL,file_list,source_dir)
# removes all files listed in $(1) from target directory $(DESTDIR)$(2).
#
# Maintenance reminder:
# The while/rmdir loop is there to clean up empty dirs left over by
# the uninstall. This is very arguable but seems more or less
# reasonable. The loop takes care to stop when it reaches $(DESTDIR),
# since DESTDIR is presumably (but not necessarily) created by another
# authority.
ShakeNMake.CALL.UNINSTALL =  $(call ShakeNMake.CALL.INSTALL.grep_kludge,$(1)); \
	tgtdir="$(DESTDIR)$(2)"; \
	test -e "$${tgtdir}" || exit 0; \
	for b in $(1) ""; do test -z "$$b" && continue; \
		fp="$${tgtdir}/$$b"; test -e "$$fp" || continue; \
		cmd="rm $$fp"; echo $$cmd; $$cmd || exit $$?; \
	done; \
	tgtdir="$(2)"; \
	while test x != "x$${tgtdir}" -a '$(prefix)' != "$${tgtdir}" \
		-a '/' != "$${tgtdir}" -a -d "$(DESTDIR)$${tgtdir}"; do \
		rmdir $(DESTDIR)$${tgtdir} 2>/dev/null || break; \
		echo "Removing empty dir: $(DESTDIR)$${tgtdir}"; \
		tgtdir=$${tgtdir%/*}; \
	done; true

ShakeNMake.INSTALL.flags.nonbins = -m 0644
ShakeNMake.INSTALL.flags.bins = -s -m 0755
ShakeNMake.INSTALL.flags.bin-scripts = -m 0755
ShakeNMake.INSTALL.flags.dlls = -m 0755
#.PHONY: install-subdirs
#install: subdirs-install
#install-subdirs: subdirs-install
#.PHONY: uninstall-subdirs
#uninstall-subdirs: subdirs-uninstall
#uninstall: subdirs-uninstall

########################################################################
# $(call ShakeNMake.CALL.define-install-set,SET_NAME,dest_dir,install_flags)
define ShakeNMake.EVAL.define-install-set
$(if $(1),,$(error ShakeNMake.CALL.define-install-set requires an install set name as $$1))
$(if $(2),,$(error ShakeNMake.CALL.define-install-set requires an installation path as $$2))

$(if $(ShakeNMake.install.$(1).dupecheck),$(error ShakeNMake.CALL.define-install-set: rules for $1 have already been created. \
	You cannot create them twice.))
ShakeNMake.install.$(1).dupecheck := 1
ShakeNMake.install.$(1).dest ?= $(2)
ShakeNMake.install.$(1).install-flags ?= $(3)

.PHONY: install-$(1)
install-$(1):
	@test x = "x$$(ShakeNMake.install.$(1))" && exit 0; \
	$$(call ShakeNMake.CALL.INSTALL,$$(ShakeNMake.install.$(1)),$$(ShakeNMake.install.$(1).dest),$$(ShakeNMake.install.$(1).install-flags))
install: install-$(1)

.PHONY: uninstall-$(1)
uninstall-$(1):
	@test x = "x$$(ShakeNMake.install.$(1))" && exit 0; \
	$$(call ShakeNMake.CALL.UNINSTALL,$$(ShakeNMake.install.$(1)),$$(ShakeNMake.install.$(1).dest))
uninstall: uninstall-$(1)
endef
ShakeNMake.CALL.define-install-set = $(eval $(call ShakeNMake.EVAL.define-install-set,$(1),$(2),$(3)))
# set up the initial install locations and install flags:
ShakeNMake.INSTALL.target_basenames := bins sbins \
				bin-scripts \
				libs dlls \
				package_libs package_dlls \
				headers package_headers \
				package_data docs \
				man1 man2 man3 man4 \
				man5 man6 man7 man8 man9
$(call ShakeNMake.CALL.define-install-set,bins,$(prefix)/bin,$(ShakeNMake.INSTALL.flags.bins))
$(call ShakeNMake.CALL.define-install-set,bin-scripts,$(prefix)/bin,$(ShakeNMake.INSTALL.flags.bin-scripts))
#$(call ShakeNMake.CALL.define-install-set,sbins,$(prefix)/sbin,$(ShakeNMake.INSTALL.flags.bins))
$(call ShakeNMake.CALL.define-install-set,libs,$(prefix)/lib,$(ShakeNMake.INSTALL.flags.nonbins))
$(call ShakeNMake.CALL.define-install-set,dlls,$(prefix)/lib,$(ShakeNMake.INSTALL.flags.dlls))
#$(call ShakeNMake.CALL.define-install-set,package_libs,$(prefix)/lib/$(package.name),$(ShakeNMake.INSTALL.flags.nonbins))
#$(call ShakeNMake.CALL.define-install-set,package_dlls,$(prefix)/lib/$(package.name),$(ShakeNMake.INSTALL.flags.dlls))
#$(call ShakeNMake.CALL.define-install-set,headers,$(prefix)/include,$(ShakeNMake.INSTALL.flags.nonbins))
#$(call ShakeNMake.CALL.define-install-set,package_headers,$(prefix)/include/$(package.name),$(ShakeNMake.INSTALL.flags.nonbins))
#$(call ShakeNMake.CALL.define-install-set,package_data,$(prefix)/share/$(package.name),$(ShakeNMake.INSTALL.flags.nonbins))
#$(call ShakeNMake.CALL.define-install-set,docs,$(prefix)/share/doc/$(package.name),$(ShakeNMake.INSTALL.flags.nonbins))
# Set up man page entries...
$(foreach NUM,1 2 3 4 5 6 7 8 9,$(call \
	ShakeNMake.CALL.define-install-set,man$(NUM),$(prefix)/share/man/man$(NUM),$(ShakeNMake.INSTALL.flags.nonbins)))
endif
# /install
########################################################################

Deleted signify/fnc-03-release.pub.

1
2


-
-
untrusted comment: fnc 0.3 public key
RWSXIKpSr2F8z3tjmWW3pcJvNH07ArhQ8jkiA/b7weZbyS+Q7R2DG28g

Added signify/fnc-05-release.pub.



1
2
+
+
untrusted comment: fnc 0.5 public key
RWQTvScFdMzcwQlljPIt0yPn6wpR+T1kR1w0/3HMegAaYyO32FMuzMcM

Deleted src/Makefile.in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

















































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
all:
include ../subdir-inc.make
DISTCLEAN_FILES += Makefile

THE_OBJ := libfossil.o
ifneq (,$(wildcard sqlite3.c))
  HAVE_OWN_SQLITE := 1
  CPPFLAGS += -DSQLITE_CORE
  THE_OBJ += sqlite3.o
else
  HAVE_OWN_SQLITE := 0
endif
CLEAN_FILES += $(THE_OBJ)

# These are the flags used by fossil's embedded sqlite3:
sqlite3.o: CPPFLAGS+=-DNDEBUG=1 \
                 -DSQLITE_DQS=0 \
                 -DSQLITE_THREADSAFE=0 \
                 -DSQLITE_DEFAULT_MEMSTATUS=0 \
                 -DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 \
                 -DSQLITE_LIKE_DOESNT_MATCH_BLOBS \
                 -DSQLITE_OMIT_DECLTYPE \
                 -DSQLITE_OMIT_PROGRESS_CALLBACK \
                 -DSQLITE_OMIT_SHARED_CACHE \
                 -DSQLITE_OMIT_LOAD_EXTENSION \
                 -DSQLITE_MAX_EXPR_DEPTH=0 \
                 -DSQLITE_USE_ALLOCA \
                 -DSQLITE_ENABLE_LOCKING_STYLE=0 \
                 -DSQLITE_DEFAULT_FILE_FORMAT=4 \
                 -DSQLITE_ENABLE_EXPLAIN_COMMENTS \
                 -DSQLITE_ENABLE_FTS4 \
                 -DSQLITE_ENABLE_DBSTAT_VTAB \
                 -DSQLITE_ENABLE_JSON1 \
                 -DSQLITE_ENABLE_FTS5 \
                 -DSQLITE_ENABLE_STMTVTAB \
                 -DSQLITE_HAVE_ZLIB \
                 -DSQLITE_INTROSPECTION_PRAGMAS \
                 -DSQLITE_ENABLE_DBPAGE_VTAB \
                 -DSQLITE_TRUSTED_SCHEMA=0

# FIXME: update libf sql tracing: -DSQLITE_OMIT_DEPRECATED

sqlite3.o: CFLAGS+=-Wno-sign-compare
ifneq (,$(filter clang,$(CC)))
# Workaround for clang
sqlite3.o: CFLAGS+=-Wno-unused-const-variable
endif

all: $(THE_OBJ)

Added src/fnc.1.





































































































































































































































































































































































































































































































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
671
672
673
674
675
676
677
678
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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
.\"
.\" Copyright (c) 2021 Mark Jamsek <mark@jamsek.com>
.\"
.\" Permission to use, copy, modify, and distribute this software for any
.\" purpose with or without fee is hereby granted, provided that the above
.\" copyright notice and this permission notice appear in all copies.
.\"
.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
.\"
.Dd $Mdocdate$
.Dt FNC 1
.Os
.Sh NAME
.Nm fnc
.Nd Read-only ncurses-based Fossil repository browser
.Sh SYNOPSIS
.Nm
.Op Ar command
.Op Fl h | -help
.Nm
.Op Fl h | -help
.Op Fl v | -version
.Nm
.Cm timeline
.Op Fl Cz
.Op Fl T Ar tag
.Op Fl b Ar branch
.Op Fl c Ar commit
.Op Fl n Ar number
.Op Fl t Ar type
.Op Fl u Ar user
.Op Ar path
.Nm
.Cm diff
.Op Fl Ciw
.Op Fl x Ar number
.Op Ar artifact1 Op Ar artifact2
.Op Ar path ...
.Nm
.Cm tree
.Op Fl C
.Op Fl c Ar commit
.Op Ar path
.Nm
.Cm blame
.Op Fl C
.Op Fl c Ar commit Op Fl r
.Op Fl n Ar number
.Ar path
.Nm
.Cm branch
.Op Fl Ccopr
.Op Fl a Ar date | Fl b Ar date
.Op Fl s Ar order
.Op Ar glob
.Nm
.Op Ar path
.Sh DESCRIPTION
.Nm
is an interactive read-only browser for
.Xr fossil 1
repositories,
and supports multiple views to display repository data:
.Bl -tag -width Ds
.It Timeline view
Display commits from the repository's history in chronologically
descending order.
.Br
If no
.Ar command
or
.Ar arg
are specified, or just a
.Ar path
is passed,
.Nm
will default to displaying this view.
.It Diff view
Display changes introduced in the specified commit, or between two repository
artifacts.
.It Tree view
Display navigable tree reflecting the repository state as at the specified
commit.
.It Blame view
Display and annotate each line in the given file with the hyperlinked historical
version that last modified the line.
.It Branch view
Display navigable list of all repository branches.
.El
.Pp
.Nm
provides both global and command-specific options and in-app key
bindings.  Global options are specified absent a command name, and
are as follows:
.Bl -tag -width 6v
.It Fl h , -help
Display program help and usage information then exit.
.It Fl v , -version
Display program version then exit.
.El
.Pp
Note that any global options preceding a command name will be
interpreted as the command-specific variant if such an option exists.
.Pp
Global key bindings are as follows:
.Bl -tag -width Ds
.It Cm H, ?, F1
Open in-app help.
.It Cm Tab
Switch focus between open views.
.It Cm f
Toggle the active view between fullscreen and splitscreen mode.  Note
that
.Nm
will open nested views in splitscreen mode if the terminal window is
equal to or greater than 110 columns wide.
.It Cm Q
Immediatey quit
.Nm .
.It Cm q
Quit the active view.
.El
.Pp
Commands available to
.Nm
are as follows:
.Bl -tag -width 4v
.Tg log
.It Cm timeline Oo Fl C | -no-colour Oc Oo Fl T | -tag Ar tag Oc \
Oo Fl b | -branch Ar branch Oc Oo Fl c | -commit Ar commit Oc \
Oo Fl h | -help Oc  Oo Fl n | -limit Ar n Oc  Oo Fl t | -type Ar type Oc \
Oo Fl u | -username Ar user Oc Oo Fl z | -utc Oc  Op Ar path
.Dl (aliases: Cm log , Cm tl , Cm time , Cm ti )
Display commit history of a repository.  If
.Ar path
is specified, only commits that modified the file(s) at this path will populate
the timeline.  The
.Ar path
may be absolute, relative to the current working directory, or relative to the
repository root.  This command must be executed from within or below the top
level directory of the repository; that is,
.Nm
assumes a local checkout is open in or above the current working directory.
.Pp
If no command is explicitly specified, this command will be executed by
default.
.Pp
Options for
.Cm fnc timeline
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable colourised timeline, which is enabled by default on supported
terminals. If this option is not used, colour can be toggled with the
.Sy c
timeline view key binding as documented below.
.It Fl T , -tag Ar tag
Only display commits with T cards containing
.Ar tag .
By default,
.Nm
will indiscriminately display all commits irrespective of which T cards
are attached to the commit manifest.
.It Fl b , -branch Ar branch
Display commits that are members of the specified
.Ar branch .
The expected argument is the symbolic name of a branch. By default,
.Nm
will display all commits irrespective of the branch on which they
reside.
.It Fl c , -commit Ar commit
Open the timeline from the check-in identified by
.Ar commit .
The expected argument is either the name of a branch, which will resolve
to the latest commit on the given branch, or (a unique abbreviated
prefix of) a valid commit UUID SHA1 or SHA3 hash. When this option is
not supplied,
.Nm
will open the timeline to the latest leaf on the repository tree.  For a
complete list of valid arguments this option accepts, see
.Lk https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki \
"Fossil's Check-in Names".
.It Fl h , -help
Display timeline command help and usage information then exit.
.It Fl n , -limit Ar n
Limit timeline to the
latest
.Ar n
commits.
By default,
.Nm
will load the entire history of the repository's local checkout.
Negative values are a no-op.
.It Fl t , -type Ar type
Only display
.Ar type
commits. Valid
.Ar type
values are as follows:
.Bl -column YXZ description
.Sy ci Ta check-in
.Sy w Ta wiki
.Sy t Ta ticket
.Sy e Ta technote
.Sy f Ta forum post
.El
.Pp
By default, when this option is not supplied,
.Nm
will indiscriminately load all commits irrespective of
.Ar type .
Note that this is a repeatable flag (e.g.,
.Nm
.Cm timeline
.Cm -t e -t t Ns
).
.It Fl u , -username Ar user
Only display commits authored by
.Ar user .
.It Fl z , -utc
Use Coordinated Universal Time (UTC) rather than local time when
displaying commit dates and timestamps.
.El
.Pp
Key bindings for
.Cm fnc timeline
are as follows:
.Bl -tag -width Ds
.It Cm Arrow-down, j, >, \&.
Move selection cursor down the timeline.
.It Cm Arrow-up, k, <, \&,
Move selection cursor up the timeline.
.It Cm Ctrl+f, Page-down
Move selection cursor one page down the timeline.
.It Cm Ctrl+b, Page-up
Move selection cursor one page up the timeline.
.It Cm G, End
Move selection cursor to the last commit on the timeline (i.e., oldest commit
in the repository).
.It Cm gg, Home
Move selection cursor to the first commit on the timeline (i.e., newest commit
in the repository).
.It Cm Enter, Space
Open a
.Cm diff
view displaying the changeset of the currently selected commit.
.It Cm c
Toggle colourised timeline. On supported terminals,
.Nm
will default to displaying the timeline in colour.
.It Cm t
Display the tree of the repository corresponding to the currently selected
commit.
.It Cm /
Prompt to enter a search term to begin searching for commits matching
the pattern provided.  The search term is an extended regular expression,
which is cross-referenced against a commit's comment, the username of
its author, branch, and UUID SHA1 or SHA3 hash.  See
.Xr re_format 7
for regular expression syntax.
.It Cm n
Find the next commit that matches the current search term.  The search
will continue until either a match is found or the earliest commit on
the timeline is consumed.
.It Cm N
Find the previous commit that matches the current search term.  The
search will continue until either a match is found or the latest commit
on the timeline is consumed.
.El
.Tg di
.It Cm diff Oo Fl C | -no-colour Oc Oo Fl h | -help Oc Oo Fl i | -invert \
Oc Oo Fl w | -whitespace Oc Oo Fl x | -context Ar n Oc \
Oo Ar artifact1 Oo Ar artifact2 Oc Oc Op Ar path ...
.Dl (alias: Cm di )
Display the differences between two repository artifacts, or between the local
changes on disk and a given commit.  If neither
.Ar artifact1
nor
.Ar artifact2
are specified,
.Nm
will diff the local changes on disk against the version on which the current
checkout is based.  If only
.Ar artifact1
is specified,
.Nm
will diff the current checkout, including any local changes on disk, against
this version.  When both arguments are specified, the changes between these two
versions will be displayed.  If supplied,
.Nm
will filter diffs between commits by
.Ar path
so that only changes involving the file(s) identified are displayed.  Paths may
be absolute, relative to the current working directory, or relative to the
repository root.  Both
.Ar artifact1
and
.Ar artifact2
must be of the same type, which is expected to be either a symbolic check-in
name, tag, (unique abbreviated prefix of) a commit or blob artifact UUID SHA1
or SHA3 hash, or an ISO 8601 formatted date. Both artifact arguments must be
supplied when diffing blobs; any following non-option arguments are invalid
and will be ignored.
.Pp
Options for
.Cm fnc diff
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured diff output, which is enabled by default on supported
terminals. If this option is not used, colour can be toggled with the
.Sy c
diff view key binding as documented below.
.It Fl h , -help
Display diff command help and usage information then exit.
.It Fl i , -invert
Invert the difference between artifacts when displaying the diff.
.It Fl w , -whitespace
Ignore whitespace-only changes when displaying the diff.
.It Fl x , -context Ar n
Set
.Ar n
context lines to be shown in the diff.  By default, 5 context lines are
shown. Negative values are a no-op.
.El
.Pp
Key bindings for
.Cm fnc diff
are as follows:
.Bl -tag -width Ds
.It Cm c
Toggle coloured diff output. On supported terminals,
.Nm
will default to displaying changes and diff metadata in colour.
.It Cm i
Toggle inversion of diff output.
.It Cm v
Toggle verbosity of diff output. By default,
.Nm
will display the entire content of newly added or deleted files.
.It Cm w
Toggle whether whitespace-only changes are ignored when comparing lines in the
diff.
.It Cm Arrow-down, j
Scroll down one line of diff output.
.It Cm Arrow-up, k
Scroll up one line of diff output.
.It Cm Ctrl+f, Page-down, Space
Scroll down one page of diff output.
.It Cm Ctrl+b, Page-up
Scroll up one page of diff output.
.It Cm G, End
Scroll to the end of the view (i.e., last line of diff output).
.It Cm gg, Home
Scroll to the top of the view (i.e., first line of diff output).
.It Cm \&-, \&_
Decrease the number of context lines shown in diff output.
.It Cm \&=, \&+
Increase the number of context lines shown in diff output.
.It Cm Ctrl+k, K, <, \&,
Move up the
.Cm timeline
to the previous (i.e., more recent) commit and display its diff.
.It Cm Ctrl+j, J, >, \&.
Move down the
.Cm timeline
to the next (i.e., earlier) commit and display its diff.
.It Cm /
Prompt to enter a search term to begin searching the diff output for
lines matching the pattern provided.  The search term is an extended
regular expression, which is documented in
.Xr re_format 7 .
.It Cm n
Find the next line that matches the current search term.
.It Cm N
Find the previous line that matches the current search term.
.El
.Tg dir
.It Cm tree Oo Fl C | -no-colour Oc Oo Fl c | -commit Ar commit Oc \
Oo Fl h | -help Oc Op Ar path
.Dl (aliases: Cm dir , Cm tr )
Display navigable, hierarchical tree of a repository.  If a
.Ar path
is specified, display tree nodes of this path.  The
.Ar path
may be absolute, relative to the current working directory, or relative to the
repository root.  With no options passed, the tree will reflect the state of the
latest commit on trunk.  This command must be executed from within or below the
top level directory of the repository; that is,
.Nm
assumes a local checkout is open in or above the current working directory.
.Pp
Tree nodes are lexicographically ordered and may be postfixed with an identifier
corresponding to the mode of the file object on disk as returned by
.Xr lstat 2 :
.Bl -column YXZ description
.It / Ta directory
.It * Ta executable
.It @ Ta symbolic link
.El
.Pp
Nodes representing symbolic links are also annotated with the path of the
source file.
.Pp
Options for
.Cm fnc tree
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured output, which is enabled by default on supported terminals.
If this option is not used, colour can be toggled with the
.Sy c
tree view key binding as documented below.
.It Fl c , -commit Ar commit
The displayed tree will reflect the state of the repository as at the check-in
identified by
.Ar commit .
The expected argument is either the name of a branch, which will resolve
to the latest commit on the given branch, or (a unique abbreviated
prefix of) a valid commit UUID SHA1 or SHA3 hash.  For a complete list of valid
arguments this option accepts, see
.Lk https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki \
"Fossil's Check-in Names".
.It Fl h , -help
Display tree command help and usage information then exit.
.El
.Pp
Key bindings for
.Cm fnc tree
are as follows:
.Bl -tag -width Ds
.It Cm Enter, Arrow-right, l
Enter the currently selected directory, or open a
.Cm blame
view of the currently selected file.
.It Cm Backspace, Arrow-left, h
Move up a level to the parent directory.  This is a no-op when in the root tree.
.It Cm Arrow-down, j
Move selection cursor one node down the tree.
.It Cm Arrow-up, k
Move selection cursor one node up the tree.
.It Cm Page-down, Ctrl+f
Move selection cursor one page down the tree.
.It Cm Page-up, Ctrl+b
Move selection cursor one page up the tree.
.It Cm Home, gg
Move selection cursor to the first node in the tree.
.It Cm End, G
Move selection cursor to the last node in the tree.
.It Cm c
Toggle coloured output. On supported terminals,
.Nm
will default to displaying the tree in colour.
.It Cm t
Open
.Cm timeline
view for the currently selected tree node.  This will display the timeline of
all commits that involve the versioned file(s) corresponding to the selected
node.
.It Cm i
Show SHA hash UUID for all file nodes displayed in the tree.
.It Cm /
Prompt to enter a search term to begin searching the tree for nodes matching the
entered pattern.  The search term is an extended regular expression, as
documented in
.Xr re_format 7 ,
and is matched against the path of each tree node.
.It Cm n
Find the next tree node that matches the current search pattern.
.It Cm N
Find the previous tree node that matches the current search pattern.
.El
.Tg praise
.It Cm blame Oo Fl C | -no-colour Oc \
Oo Fl c | -commit Ar commit Oo Fl r | -reverse Oc Oc Oo Fl h | -help Oc \
Oo Fl n | -limit Ar n Oc Ar path
.Dl (aliases: Cm praise , Cm annotate , Cm bl , Cm pr , Cm an )
Show commit attribution history for each line of the file at the specified
.Ar path ,
which may be absolute, relative to the current working directory, or relative to
the repository root.  This command must be executed from within or below the top
level directory of the repository; that is,
.Nm
assumes a local checkout is open in or above the current working directory.
.Pp
Options for
.Cm fnc blame
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured output, which is enabled by default on supported terminals.
If this option is not used, colour can be toggled with the
.Sy c
blame view key binding as documented below.
.It Fl c , -commit Ar commit
Start blame of file at the specified
.Ar path
from the check-in identified by
.Ar commit .
The expected argument is either the name of a branch, which will resolve
to the latest commit on the given branch, or (a unique abbreviated
prefix of) a valid commit UUID SHA1 or SHA3 hash. When this option is
not supplied,
.Nm
will blame the version of the file from the current checkout.  For a complete
list of valid arguments this option accepts, see
.Lk https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki \
"Fossil's Check-in Names".
.It Fl h , -help
Display blame command help and usage information then exit.
.It Fl n , -limit Ar n
Limit depth of blame history to
.Ar n
commits or seconds.  The latter is denoted by a postfixed 's' (e.g., 30s).
With this option,
.Nm
will traverse either as many commits as specified, or as possible in the
specified time limit.  By default,
.Nm
will traverse the entire historical record of the file, which can be expensive
for large files that span many commits. Use this option for a faster, more
targeted annotation.
.It Fl r , -reverse
Reverse annotate the file starting from a historical commit and move forward in
time. That is, rather than show the most recent change to each line, show the
first time each line was modified by a subsequent commit after the specified
.Ar commit .
(Requires \fB\-c\fP|\fB\-\-commit\fP.)
.El
.Pp
Key bindings for
.Cm fnc blame
are as follows:
.Bl -tag -width Ds
.It Cm Arrow-down, j
Move selection cursor down one line.
.It Cm Arrow-up, k
Move selection cursor up one line.
.It Cm Page-down, Ctrl+f
Move selection cursor down one page.
.It Cm Page-up, Ctrl+b
Move selection cursor up one page.
.It Cm Home, gg
Move selection cursor to the first line in the file.
.It Cm End, G
Move selection cursor to the last line in the file.
.It Cm Enter
Display the
.Cm diff
of the commit corresponding to the currently selected line.
.It Cm b
Blame the version of the file corresponding to the commit in the currently
selected line.
.It Cm p
Blame the version of the file corresponding to the parent of the commit in
the currently selected line.
.It Cm B, Backspace
Reload the previous blamed version of the file.
.It Cm c
Toggle coloured output. On supported terminals,
.Nm
will default to displaying the blamed file in colour.
.It Cm /
Prompt to enter a search term to begin searching the file for tokens matching
the entered pattern.  The search term is an extended regular expression, as
documented in
.Xr re_format 7 .
.It Cm n
Find the next token that matches the current search pattern.
.It Cm N
Find the previous token that matches the current search pattern.
.El
.Tg tag
.It Cm branch Oo Fl C | -no-colour Oc Oo Fl -after Ar date | \
Fl -before Ar date Oc Oo Fl h | -help Oc Oo Fl -open | Fl -closed Oc \
Oo Fl p | -no-private Oc Oo Fl r | -reverse Oc \
Oo Fl s | -sort Ar order Oc Op Ar glob
.Dl (aliases: Cm tag , Cm br )
Display navigable list of repository branches. If
.Ar glob ,
is specified, only display branches matching the pattern provided. Pattern
matching comparisons depend on the
.Xr sqlite3 1
.B
LIKE
operator, which only folds case for the ASCII character set.  This
command must be executed from within or below the top level directory of the
repository; that is,
.Nm
assumes a local checkout is open in or above the current working directory.
.Pp
Branches are lexicographically ordered by default, and are prefixed with an
identifier corresponding to the branch state (i.e., open/closed). The
current and private branches are additionally annotated with a postfixed
identifier:
.Bl -column ABCDEFGHIJ description
.It +dev-foo Ta open
.It -rm-bar Ta closed
.It +trunk@ Ta current
.It +wip-baz* Ta private
.El
.Pp
All branches, irrespective of state or privacy, are displayed by default, but
can be filtered based on several characteristics.
.Pp
Options for
.Cm fnc branch
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured output, which is enabled by default on supported terminals.
If this option is not used, colour can be toggled with the
.Sy c
branch view key binding as documented below.
.It Fl a , -after Ar date
Display only those branches with activity after the specified
.Ar date .
.It Fl b , -before Ar date
Display only those branches with activity before the specified
.Ar date .
.It Fl c , -close
Display only closed branches.
.It Fl h , -help
Display branch command help and usage information then exit.
.It Fl o , -open
Display only opened branches.
.It Fl p , -no-private
Do not show private branches, which are included in the list of displayed
branches by default.
.It Fl r , -reverse
Reverse the order in which branches are displayed.
.It Fl s , -sort Ar order
Sort branches by
.Ar order .
Valid
.Ar order
values are as follows:
.Bl -column YXZ description
.Sy mru Ta most recently used
.Sy state Ta open/closed state
.El
.Pp
Branches are sorted in lexicographical order by default.
.El
.Pp
Key bindings for
.Cm fnc branch
are as follows:
.Bl -tag -width Ds
.It Cm Arrow-down, j
Move selection cursor down one branch.
.It Cm Arrow-up, k
Move selection cursor up one branch.
.It Cm Page-down, Ctrl+f
Move selection cursor down one page.
.It Cm Page-up, Ctrl+b
Move selection cursor up one page.
.It Cm Home, gg
Move selection cursor to the first branch in the list.
.It Cm End, G
Move selection cursor to the last branch in the list.
.It Cm Enter, Space
Display the
.Cm timeline
of the currently selected branch.
.It Cm c
Toggle coloured output.  On supported terminals,
.Nm
will default to displaying the branch list in colour.
.It Cm d
Toggle display of the date on which the branch last received changes.
.It Cm i
Toggle display of the SHA{1,3} hash that identifies branch, which is the hash
of the commit on the tip of said branch.
.It Cm t
Open the
.Cm tree
view of the currently selected branch.
.It Cm R, Ctrl+l
Reload the view with all repository branches, irrespective of which options
were used in this
.Cm fnc branch
invocation.
.It Cm /
Prompt to enter a search term to begin searching the list for branches matching
the entered pattern.  The search term is an extended regular expression, as
documented in
.Xr re_format 7 .
.It Cm n
Find the next branch that matches the current search pattern.
.It Cm N
Find the previous branch that matches the current search pattern.
.El
.El
.Sh EXIT STATUS
.Ex -std fnc
.Sh SEE ALSO
.Xr fossil 1 ,
.Xr re_format 7
.Xr sqlite3 1
.Sh AUTHOR
.An Mark Jamsek Aq Mt mark@jamsek.com

Added src/fnc.c.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
671
672
673
674
675
676
677
678
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
737
738
739
740
741
742
743
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
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
817
818
819
820
821
822
823
824
825
826
827
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
860
861
862
863
864
865
866
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
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
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
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
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
1342
1343
1344
1345
1346
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
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
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
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
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
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
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
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
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
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
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
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
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
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
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
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
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
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
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
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
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
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
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
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
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
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
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
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
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
3578
3579
3580
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
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
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
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
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
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
3931
3932
3933
3934
3935
3936
3937
3938
3939
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
3977
3978
3979
3980
3981
3982
3983
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
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
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
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
4182
4183
4184
4185
4186
4187
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
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
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
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
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
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
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
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
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
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * Copyright (c) 2021 Mark Jamsek <mark@jamsek.com>
 * Copyright (c) 2013-2021 Stephan Beal <https://wanderinghorse.net>
 * Copyright (c) 2020 Stefan Sperling <stsp@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * This _POSIX_C_SOURCE bit really belongs in a config.h, but in the
 * name of expedience...
 */
#if defined __linux__
#  if !defined(_XOPEN_SOURCE)
#    define _XOPEN_SOURCE 700
/*
 * _POSIX_C_SOURCE >= 199309L needed for sigaction(), sigemptyset() on Linux,
 * but glibc docs claim that _XOPEN_SOURCE>=700 has the same effect, PLUS
 * we need _XOPEN_SOURCE>=500 for ncurses wide-char APIs on linux.
 */
#  endif
#  if !defined(_DEFAULT_SOURCE)
#    define _DEFAULT_SOURCE
/* Needed for strsep() on glibc >= 2.19. */
#  endif
#endif


#include <sys/queue.h>
#include <sys/ioctl.h>
#include <sys/stat.h>

#ifdef _WIN32
#include <windows.h>
#define ssleep(x) Sleep(x)
#else
#define ssleep(x) usleep((x) * 1000)
#endif
#include <ctype.h>
#include <curses.h>
#include <panel.h>
#include <locale.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <err.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
#include <pthread.h>
#include <libgen.h>
#include <regex.h>
#include <signal.h>
#include <wchar.h>
#include <langinfo.h>

#include "libfossil.h"

#define FNC_VERSION	VERSION  /* cf. Makefile */

/* Utility macros. */
#define MIN(a, b)	(((a) < (b)) ? (a) : (b))
#define MAX(a, b)	(((a) > (b)) ? (a) : (b))
#if !defined(CTRL)
#define CTRL(key)	((key) & 037)	/* CTRL+<key> input. */
#endif
#define nitems(a)	(sizeof((a)) / sizeof((a)[0]))
#define STRINGIFYOUT(s)	#s
#define STRINGIFY(s)	STRINGIFYOUT(s)
#define CONCATOUT(a, b)	a ## b
#define CONCAT(a, b)	CONCATOUT(a, b)
#define FILE_POSITION	__FILE__ ":" STRINGIFY(__LINE__)
#define FLAG_SET(f, b)	((f) |= (b))
#define FLAG_CHK(f, b)	((f) & (b))
#define FLAG_TOG(f, b)	((f) ^= (b))
#define FLAG_CLR(f, b)	((f) &= ~(b))

/* Application macros. */
#define PRINT_VERSION	STRINGIFY(FNC_VERSION)
#define DIFF_DEF_CTXT	5		/* Default diff context lines. */
#define DIFF_MAX_CTXT	64		/* Max diff context lines. */
#define SPIN_INTERVAL	200		/* Status line progress indicator. */
#define SPINNER		"\\|/-\0"
#define NULL_DEVICE	"/dev/null"
#define NULL_DEVICELEN	(sizeof(NULL_DEVICE) - 1)
#define KEY_ESCAPE	27
#if DEBUG
#define RC(r, fmt, ...)	fcli_err_set(r, "%s::%s " fmt,			\
			    __func__, FILE_POSITION, __VA_ARGS__)
#else
#define RC(r, fmt, ...) fcli_err_set(r, fmt, __VA_ARGS__)
#endif /* DEBUG */

/* Portability macros. */
#ifndef __OpenBSD__
#ifndef HAVE_STRTONUM
#  define strtonum(s, min, max, o) strtol(s, (char **)o, 10)
# endif /* HAVE_STRTONUM */
#endif

#if !defined(__dead)
#define __dead
#endif

#ifndef TAILQ_FOREACH_SAFE
/* Rewrite of OpenBSD 6.9 sys/queue.h for Linux builds. */
#define TAILQ_FOREACH_SAFE(var, head, field, tmp)			\
	for ((var) = ((head)->tqh_first);				\
		(var) != (NULL) && ((tmp) = TAILQ_NEXT(var, field), 1);	\
		(var) = (tmp))
#endif

/*
 * STAILQ was added to OpenBSD 6.9; fallback to SIMPLEQ for prior versions.
 * XXX This is an ugly hack; replace with a better solution.
 */
#ifdef __OpenBSD__
# ifndef STAILQ_HEAD
#  define STAILQ SIMPLEQ
# endif /* STAILQ_HEAD */
#endif /* OpenBSD */

#if defined __linux__
# ifndef strlcat
#  define strlcat(_d, _s, _sz) fsl_strlcat(_d, _s, _sz)
# endif /* strlcat */
# ifndef strlcpy
#  define strlcpy(_d, _s, _sz) fsl_strlcpy(_d, _s, _sz)
# endif /* strlcpy */
#endif /* __linux__ */

__dead static void	usage(void);
static void		usage_timeline(void);
static void		usage_diff(void);
static void		usage_tree(void);
static void		usage_blame(void);
static void		usage_branch(void);
static int		fcli_flag_type_arg_cb(fcli_cliflag const *);
static int		cmd_timeline(fcli_command const *);
static int		cmd_diff(fcli_command const *);
static int		cmd_tree(fcli_command const *);
static int		cmd_blame(fcli_command const *);
static int		cmd_branch(fcli_command const *);

/*
 * Singleton initialising global configuration and state for app startup.
 */
static struct fnc_setup {
	/* Global options. */
	const char	*cmdarg;	/* Retain argv[1] for use/err report. */
	const char	*sym;		/* Open view from this symbolic name. */
	const char	*path;		/* Optional path for timeline & tree. */
	int		 err;		/* Indicate fnc error state. */
	bool		 hflag;		/* Flag if --help is requested. */
	bool		 vflag;		/* Flag if --version is requested. */
	bool		 reverse;	/* Reverse branch sort or blame. */

	/* Timeline options. */
	struct artifact_types {
		const char	**values;
		short		  nitems;
	} *filter_types;		/* Only load commits of <type>. */
	union {
		const char	 *zlimit;
		int		  limit;
	} nrecords;			/* Number of commits to load. */
	const char	*filter_tag;	/* Only load commits with <tag>. */
	const char	*filter_branch;	/* Only load commits from <branch>. */
	const char	*filter_user;	/* Only load commits from <user>. */
	const char	*filter_type;	/* Placeholder for repeatable types. */
	bool		 utc;		/* Display UTC sans user local time. */

	/* Diff options. */
	const char	*context;	/* Number of context lines. */
	bool		 ws;		/* Ignore whitespace-only changes. */
	bool		 nocolour;	/* Disable colour in diff output. */
	bool		 quiet;		/* Disable verbose diff output. */
	bool		 invert;	/* Toggle inverted diff output. */

	/* Branch options. */
	const char	*before;	/* Last branch change before date. */
	const char	*after;		/* Last branch change after date. */
	const char	*sort;		/* Lexicographical, MRU, open/closed. */
	bool		 closed;	/* Show only closed branches. */
	bool		 open;		/* Show only open branches */
	bool		 noprivate;	/* Don't show private branches. */

	/* Command line flags and help. */
	fcli_help_info	  fnc_help;			/* Global help. */
	fcli_cliflag	  cliflags_global[3];		/* Global options. */
	fcli_command	  cmd_args[6];			/* App commands. */
	fcli_cliflag	  cliflags_timeline[11];	/* Timeline options. */
	fcli_cliflag	  cliflags_diff[7];		/* Diff options. */
	fcli_cliflag	  cliflags_tree[4];		/* Tree options. */
	fcli_cliflag	  cliflags_blame[6];		/* Blame options. */
	fcli_cliflag	  cliflags_branch[10];		/* Branch options. */
} fnc_init = {
	NULL,		/* cmdarg copy of argv[1] to aid usage/error report. */
	NULL,		/* sym(bolic name) of commit to open defaults to tip. */
	NULL,		/* path for tree to open or timeline to find commits. */
	0,		/* err fnc error state. */
	false,		/* hflag if --help is requested. */
	false,		/* vflag if --version is requested. */
	false,		/* reverse branch sort/annotation defaults to off. */
	NULL,		/* filter_types defaults to indiscriminate. */
	{0},		/* nrecords defaults to all commits. */
	NULL,		/* filter_tag defaults to indiscriminate. */
	NULL,		/* filter_branch defaults to indiscriminate. */
	NULL,		/* filter_user defaults to indiscriminate. */
	NULL,		/* filter_type temporary placeholder. */
	false,		/* utc defaults to off (i.e., show user local time). */
	NULL,		/* context defaults to five context lines. */
	false,		/* ws defaults to acknowledge whitespace. */
	false,		/* nocolour defaults to off (i.e., use diff colours). */
	false,		/* quiet defaults to off (i.e., verbose diff is on). */
	false,		/* invert diff defaults to off. */
	NULL,		/* before defaults to any time. */
	NULL,		/* after defaults to any time. */
	NULL,		/* sort by MRU or open/closed (dflt: lexicographical) */
	false,		/* closed only branches is off (defaults to all). */
	false,		/* open only branches is off by (defaults to all). */
	false,		/* noprivate is off (default to show private branch). */

	{ /* fnc_help global app help details. */
	    "A read-only ncurses browser for Fossil repositories in the "
	    "terminal.", NULL, usage
	},

	{ /* cliflags_global global app options. */
	    FCLI_FLAG_BOOL("h", "help", &fnc_init.hflag,
	    "Display program help and usage then exit."),
	    FCLI_FLAG_BOOL("v", "version", &fnc_init.vflag,
	    "Display program version number and exit."),
	    fcli_cliflag_empty_m
	},

	{ /* cmd_args available app commands. */
	    {"timeline", "tl\0time\0ti\0log\0",
	    "Show chronologically descending commit history of the repository.",
	    cmd_timeline, usage_timeline, fnc_init.cliflags_timeline},
	    {"diff", "di\0",
	    "Show changes to versioned files introduced with a given commit.",
	    cmd_diff, usage_diff, fnc_init.cliflags_diff},
	    {"tree", "tr\0dir\0",
	    "Show repository tree corresponding to a given commit",
	    cmd_tree, usage_tree, fnc_init.cliflags_tree},
	    {"blame", "bl\0praise\0pr\0annotate\0an\0",
	    "Show commit attribution history for each line of a file.",
	    cmd_blame, usage_blame, fnc_init.cliflags_blame},
	    {"branch", "br\0tag\0",
	    "Show navigable list of repository branches.",
	    cmd_branch, usage_branch, fnc_init.cliflags_branch},
	    {NULL, NULL, NULL, NULL, NULL}	/* Sentinel. */
	},

	{ /* cliflags_timeline timeline command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable colourised timeline, which is enabled by default on\n    "
            "supported terminals. Colour can also be toggled with the 'c' "
            "\n    key binding in timeline view when this option is not used."),
	    FCLI_FLAG("T", "tag", "<tag>", &fnc_init.filter_tag,
            "Only display commits with T cards containing <tag>."),
	    FCLI_FLAG("b", "branch", "<branch>", &fnc_init.filter_branch,
            "Only display commits that reside on the given <branch>."),
	    FCLI_FLAG("c", "commit", "<commit>", &fnc_init.sym,
            "Open the timeline from <commit>. Common symbols are:\n"
            "\tSHA{1,3} hash\n"
            "\tSHA{1,3} unique prefix\n"
            "\tbranch\n"
            "\ttag:TAG\n"
            "\troot:BRANCH\n"
            "\tISO8601 date\n"
            "\tISO8601 timestamp\n"
            "\t{tip,current,prev,next}\n    "
            "For a complete list of symbols see Fossil's Check-in Names:\n    "
            "https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki"),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display timeline command help and usage."),
	    FCLI_FLAG("n", "limit", "<n>", &fnc_init.nrecords.zlimit,
            "Limit display to <n> latest commits; defaults to entire history "
            "of\n    current checkout. Negative values are a no-op."),
	    FCLI_FLAG_X("t", "type", "<type>", &fnc_init.filter_type,
	    fcli_flag_type_arg_cb,
            "Only display <type> commits. Valid types are:\n"
            "\tci - check-in\n"
            "\tw  - wiki\n"
            "\tt  - ticket\n"
            "\te  - technote\n"
            "\tf  - forum post\n"
            "    n.b. This is a repeatable flag (e.g., -t ci -t w)."),
	    FCLI_FLAG("u", "username", "<user>", &fnc_init.filter_user,
            "Only display commits authored by <username>."),
	    FCLI_FLAG_BOOL("z", "utc", &fnc_init.utc,
            "Use UTC (instead of local) time."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_timeline. */

	{ /* cliflags_diff diff command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured diff output, which is enabled by default on\n    "
            "supported terminals. Colour can also be toggled with the 'c' "
            "\n    key binding in diff view when this option is not used."),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display diff command help and usage."),
	    FCLI_FLAG_BOOL("i", "invert", &fnc_init.invert,
            "Invert difference between artifacts. Inversion can also be "
            "toggled\n    with the 'i' key binding in diff view."),
	    FCLI_FLAG_BOOL("q", "quiet", &fnc_init.quiet,
            "Disable verbose diff output; that is, do not output complete"
            " content\n    of newly added or deleted files. Verbosity can also"
            " be toggled with\n    the 'v' key binding in diff view."),
	    FCLI_FLAG_BOOL("w", "whitespace", &fnc_init.ws,
            "Ignore whitespace-only changes when displaying diff. This option "
            "can\n    also be toggled with the 'w' key binding in diff view."),
	    FCLI_FLAG("x", "context", "<n>", &fnc_init.context,
            "Show <n> context lines when displaying diff; <n> is capped at 64."
            "\n    Negative values are a no-op."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_diff. */

	{ /* cliflags_tree tree command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured output, which is enabled by default on supported"
            "\n    terminals. Colour can also be toggled with the 'c' key "
            "binding when\n    this option is not used."),
	    FCLI_FLAG("c", "commit", "<commit>", &fnc_init.sym,
            "Display tree that reflects repository state as at <commit>.\n"
            "    Common symbols are:"
            "\n\tSHA{1,3} hash\n"
            "\tSHA{1,3} unique prefix\n"
            "\tbranch\n"
            "\ttag:TAG\n"
            "\troot:BRANCH\n"
            "\tISO8601 date\n"
            "\tISO8601 timestamp\n"
            "\t{tip,current,prev,next}\n    "
            "For a complete list of symbols see Fossil's Check-in Names:\n    "
            "https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki"),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display tree command help and usage."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_tree. */

	{ /* cliflags_blame blame command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured output, which is enabled by default on supported"
            "\n    terminals. Colour can also be toggled with the 'c' key "
            "binding when\n    this option is not used."),
	    FCLI_FLAG("c", "commit", "<commit>", &fnc_init.sym,
            "Start blame of specified file from <commit>. Common symbols are:\n"
            "\tSHA{1,3} hash\n"
            "\tSHA{1,3} unique prefix\n"
            "\tbranch\n"
            "\ttag:TAG\n"
            "\troot:BRANCH\n"
            "\tISO8601 date\n"
            "\tISO8601 timestamp\n"
            "\t{tip,current,prev,next}\n    "
            "For a complete list of symbols see Fossil's Check-in Names:\n    "
            "https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki"),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display blame command help and usage."),
            FCLI_FLAG("n", "limit", "<n>", &fnc_init.nrecords.zlimit,
	    "Limit depth of blame history to <n> commits or seconds. Denote the"
	    "\n    latter by postfixing 's' (e.g., 30s). Useful for large files"
	    " with\n    extensive history. Persists for the duration of the "
	    "session."),
            FCLI_FLAG_BOOL("r", "reverse", &fnc_init.reverse,
	    "Reverse annotate the file starting from a historical commit. "
	    "Rather\n    than show the most recent change of each line, show "
	    "the first time\n    each line was modified after the specified "
	    "commit. Requires -c|--commit."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_blame. */

	{ /* cliflags_branch branch command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured output, which is enabled by default on supported"
            "\n    terminals. Colour can also be toggled with the 'c' key "
            "binding when\n    this option is not used."),
	    FCLI_FLAG("a", "after", "<date>", &fnc_init.after,
            "Show branches with last activity occuring after <date>, which is\n"
            "    expected to be either an ISO8601 (e.g., 2020-10-10) or "
            "unambiguous\n    DD/MM/YYYY or MM/DD/YYYY formatted date."),
	    FCLI_FLAG("b", "before", "<date>", &fnc_init.before,
            "Show branches with last activity occuring before <date>, which is"
            "\n    expected to be either an ISO8601 (e.g., 2020-10-10) or "
            "unambiguous\n    DD/MM/YYYY or MM/DD/YYYY formatted date."),
            FCLI_FLAG_BOOL("c", "closed", &fnc_init.closed,
	    "Show closed branches only. Open and closed branches are listed by "
	    "\n    default."),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display branch command help and usage."),
            FCLI_FLAG_BOOL("o", "open", &fnc_init.open,
	    "Show open branches only. Open and closed branches are listed by "
	    "\n    default."),
            FCLI_FLAG_BOOL("p", "no-private", &fnc_init.noprivate,
	    "Do not show private branches, which are otherwise included in the"
	    "\n    list of displayed branches by default."),
            FCLI_FLAG_BOOL("r", "reverse", &fnc_init.reverse,
	    "Reverse the order in which branches are displayed."),
	    FCLI_FLAG("s", "sort", "<order>", &fnc_init.sort,
            "Sort branches by <order>. Available options are:\n"
            "\tmru   - most recently used\n"
            "\tstate - open/closed state\n    "
            "Branches are sorted in lexicographical order by default."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_blame. */
};

enum fsl_list_object {
	FNC_ARTIFACT_OBJ,
	FNC_COLOUR_OBJ
};

enum date_string {
	ISO8601_DATE_ONLY = 10,
	ISO8601_TIMESTAMP = 20
};

enum fnc_view_id {
	FNC_VIEW_TIMELINE,
	FNC_VIEW_DIFF,
	FNC_VIEW_TREE,
	FNC_VIEW_BLAME,
	FNC_VIEW_BRANCH
};

enum fnc_search_mvmnt {
	SEARCH_DONE,
	SEARCH_FORWARD,
	SEARCH_REVERSE
};

enum fnc_search_state {
	SEARCH_WAITING,
	SEARCH_CONTINUE,
	SEARCH_COMPLETE,
	SEARCH_NO_MATCH,
	SEARCH_FOR_END
};

enum fnc_colours {
	FNC_DIFF_META = 1,
	FNC_DIFF_MINUS,
	FNC_DIFF_PLUS,
	FNC_DIFF_CHNK,
	FNC_TREE_LINK,
	FNC_TREE_DIR,
	FNC_TREE_EXEC,
	FNC_COMMIT_ID,
	FNC_USER_STR,
	FNC_DATE_STR,
	FNC_TAGS_STR
};

enum fnc_diff_type {
	FNC_DIFF_CKOUT,
	FNC_DIFF_COMMIT,
	FNC_DIFF_BLOB,
	FNC_DIFF_WIKI
};

struct fnc_colour {
	regex_t	regex;
	uint8_t	scheme;
};

struct fsl_list_state {
	enum fsl_list_object	obj;
};

struct fnc_commit_artifact {
	fsl_buffer		 wiki;
	fsl_buffer		 pwiki;
	fsl_list		 changeset;
	fsl_uuid_str		 uuid;
	fsl_uuid_str		 puuid;
	fsl_id_t		 rid;
	fsl_id_t		 prid;
	char			*user;
	char			*timestamp;
	char			*comment;
	char			*branch;
	char			*type;
	enum fnc_diff_type	 diff_type;
};

struct fsl_file_artifact {
	fsl_card_F		*fc;
	enum fsl_ckout_change_e	 change;
};

TAILQ_HEAD(commit_tailhead, commit_entry);
struct commit_entry {
	TAILQ_ENTRY(commit_entry)	 entries;
	struct fnc_commit_artifact	*commit;
	int				 idx;
};

struct commit_queue {
	struct commit_tailhead	head;
	int			ncommits;
};

/*
 * The following two structs are used to construct the tree of the entire
 * repository; that is, from the root through to all subdirectories and files.
 */
struct fnc_repository_tree {
	struct fnc_repo_tree_node	*head;     /* Head of repository tree */
	struct fnc_repo_tree_node	*tail;     /* Final node in the tree. */
	struct fnc_repo_tree_node	*rootail;  /* Final root level node. */
};

struct fnc_repo_tree_node {
	struct fnc_repo_tree_node	*next;	     /* Next node in tree. */
	struct fnc_repo_tree_node	*prev;	     /* Prev node in tree. */
	struct fnc_repo_tree_node	*parent_dir; /* Dir containing node. */
	struct fnc_repo_tree_node	*sibling;    /* Next node in same dir */
	struct fnc_repo_tree_node	*children;   /* List of node children */
	struct fnc_repo_tree_node	*lastchild;  /* Last child in list. */
	char				*basename;   /* Final path component. */
	char				*path;	     /* Full pathname of node */
	fsl_uuid_str			 uuid;	     /* File artifact hash. */
	mode_t				 mode;	     /* File mode. */
	double				 mtime;	     /* Mod time of file. */
	uint_fast16_t			 pathlen;    /* Length of path. */
	uint_fast16_t			 nparents;   /* Path components sans- */
						     /* -basename. */
};

/*
 * The following two structs represent a given subtree within the repository;
 * for example, the top level tree and all its elements, or the elements of
 * the src/ directory (but not any members of src/ subdirectories).
 */
struct fnc_tree_object {
	struct fnc_tree_entry	*entries;  /* Array of tree entries. */
	int			 nentries; /* Number of tree entries. */
};

struct fnc_tree_entry {
	char			*basename; /* Final component of path. */
	char			*path;	   /* Full pathname of tree entry. */
	fsl_uuid_str		 uuid;	   /* File artifact hash. */
	mode_t			 mode;	   /* File mode. */
	double			 mtime;	   /* Modification time of file. */
	int			 idx;	   /* Index of this tree entry. */
};

/*
 * Each fnc_tree_object that is _not_ the repository root will have a (list of)
 * fnc_parent_tree(s) to be tracked.
 */
struct fnc_parent_tree {
	TAILQ_ENTRY(fnc_parent_tree)	 entry;
	struct fnc_tree_object		*tree;
	struct fnc_tree_entry		*first_entry_onscreen;
	struct fnc_tree_entry		*selected_entry;
	int				 selected_idx;
};

pthread_mutex_t fnc_mutex = PTHREAD_MUTEX_INITIALIZER;

struct fnc_tl_thread_cx {
	struct commit_queue	 *commits;
	struct commit_entry	**first_commit_onscreen;
	struct commit_entry	**selected_commit;
	fsl_db			 *db;
	fsl_stmt		 *q;
	regex_t			 *regex;
	char			 *path;	     /* Match commits involving path. */
	enum fnc_search_state	 *search_status;
	enum fnc_search_mvmnt	 *searching;
	int			  spin_idx;
	int			  ncommits_needed;
	/*
	 * XXX Is there a more elegant solution to retrieving return codes from
	 * thread functions while pinging between, but before we join, threads?
	 */
	int			  rc;
	bool			  tree_open;
	bool			  endjmp;
	bool			  timeline_end;
	sig_atomic_t		 *quit;
	pthread_cond_t		  commit_consumer;
	pthread_cond_t		  commit_producer;
};

struct fnc_tl_view_state {
	struct fnc_tl_thread_cx	 thread_cx;
	struct commit_queue	 commits;
	struct commit_entry	*first_commit_onscreen;
	struct commit_entry	*last_commit_onscreen;
	struct commit_entry	*selected_commit;
	struct commit_entry	*matched_commit;
	struct commit_entry	*search_commit;
	fsl_list		 colours;
	const char		*curr_ckout_uuid;
	char			*path;	     /* Match commits involving path. */
	int			 selected_idx;
	sig_atomic_t		 quit;
	pthread_t		 thread_id;
	bool			 colour;
};

struct fnc_pathlist_entry {
	TAILQ_ENTRY(fnc_pathlist_entry) entry;
	const char	*path;
	size_t		 pathlen;
	void		*data;  /* XXX May want to save id, mode, etc. */
};
TAILQ_HEAD(fnc_pathlist_head, fnc_pathlist_entry);

struct fnc_diff_view_state {
	struct fnc_view			*timeline_view;
	struct fnc_commit_artifact	*selected_commit;
	struct fnc_pathlist_head	*paths;
	fsl_buffer			 buf;
	fsl_list			 colours;
	FILE				*f;
	fsl_uuid_str			 id1;
	fsl_uuid_str			 id2;
	int				 first_line_onscreen;
	int				 last_line_onscreen;
	int				 diff_flags;
	int				 context;
	int				 sbs;
	int				 matched_line;
	int				 current_line;
	size_t				 ncols;
	size_t				 nlines;
	off_t				*line_offsets;
	bool				 eof;
	bool				 colour;
	bool				 showmeta;
};

TAILQ_HEAD(fnc_parent_trees, fnc_parent_tree);
struct fnc_tree_view_state {			  /* Parent trees of the- */
	struct fnc_parent_trees		 parents; /* -current subtree. */
	struct fnc_repository_tree	*repo;    /* The repository tree. */
	struct fnc_tree_object		*root;    /* Top level repo tree. */
	struct fnc_tree_object		*tree;    /* Currently displayed tree */
	struct fnc_tree_entry		*first_entry_onscreen;
	struct fnc_tree_entry		*last_entry_onscreen;
	struct fnc_tree_entry		*selected_entry;
	struct fnc_tree_entry		*matched_entry;
	fsl_list			 colours;
	char				*tree_label;  /* Headline string. */
	fsl_uuid_str			 commit_id;
	fsl_id_t			 rid;
	int				 ndisplayed;
	int				 selected_idx;
	bool				 colour;
	bool				 show_id;
};

struct fnc_blame_line {
	fsl_uuid_str	id;
	bool		annotated;
};

struct fnc_blame_cb_cx {
	struct fnc_view		*view;
	struct fnc_blame_line	*lines;
	fsl_uuid_str		 commit_id;
	fsl_uuid_str		 root_commit;
	int			 nlines;
	bool			*quit;
};

typedef int (*fnc_cancel_cb)(void *);

struct fnc_blame_thread_cx {
	struct fnc_blame_cb_cx	*cb_cx;
	fsl_annotate_opt	 blame_opt;
	fnc_cancel_cb		 cancel_cb;
	const char		*path;
	void			*cancel_cx;
	bool			*complete;
};

struct fnc_blame {
	struct fnc_blame_thread_cx	 thread_cx;
	struct fnc_blame_cb_cx		 cb_cx;
	FILE				*f;	/* Non-annotated copy of file */
	struct fnc_blame_line		*lines;
	off_t				*line_offsets;
	off_t				 filesz;
	fsl_id_t			 origin; /* Tip rid for reverse blame */
	int				 nlines;
	int				 nlimit;    /* Limit depth traversal. */
	pthread_t			 thread_id;
};

CONCAT(STAILQ, _HEAD)(fnc_commit_id_queue, fnc_commit_qid);
struct fnc_commit_qid {
	CONCAT(STAILQ, _ENTRY)(fnc_commit_qid) entry;
	fsl_uuid_str	 id;
};

struct fnc_blame_view_state {
	struct fnc_blame		 blame;
	struct fnc_commit_id_queue	 blamed_commits;
	struct fnc_commit_qid		*blamed_commit;
	struct fnc_commit_artifact	*selected_commit;
	fsl_list			 colours;
	fsl_uuid_str			 commit_id;
	char				*path;
	int				 first_line_onscreen;
	int				 last_line_onscreen;
	int				 selected_line;
	int				 matched_line;
	int				 spin_idx;
	bool				 done;
	bool				 blame_complete;
	bool				 eof;
	bool				 colour;
};

struct fnc_branch {
	char		*name;
	char		*date;
	fsl_uuid_str	 id;
	bool		 private;
	bool		 current;
	bool		 open;
};

struct fnc_branchlist_entry {
	TAILQ_ENTRY(fnc_branchlist_entry) entries;
	struct fnc_branch	*branch;
	int			 idx;
};
TAILQ_HEAD(fnc_branchlist_head, fnc_branchlist_entry);

struct fnc_branch_view_state {
	struct fnc_branchlist_head	 branches;
	struct fnc_branchlist_entry	*first_branch_onscreen;
	struct fnc_branchlist_entry	*last_branch_onscreen;
	struct fnc_branchlist_entry	*matched_branch;
	struct fnc_branchlist_entry	*selected_branch;
	const char			*branch_glob;
	double				 dateline;
	int				 branch_flags;
#define BRANCH_LS_CLOSED_ONLY	0x001  /* Show closed branches only. */
#define BRANCH_LS_OPEN_ONLY	0x002  /* Show open branches only. */
#define BRANCH_LS_OPEN_CLOSED	0x003  /* Show open & closed branches (dflt). */
#define BRANCH_LS_BITMASK	0x003
#define BRANCH_LS_NO_PRIVATE	0x004  /* Show public branches only. */
#define BRANCH_SORT_MTIME	0x008  /* Sort by activity. (default: name) */
#define BRANCH_SORT_STATUS	0x010  /* Sort by open/closed. */
#define BRANCH_SORT_REVERSE	0x020  /* Reverse sort order. */
	int				 nbranches;
	int				 ndisplayed;
	int				 selected;
	int				 when;
	bool				 colour;
	bool				 show_date;
	bool				 show_id;
};

TAILQ_HEAD(view_tailhead, fnc_view);
struct fnc_view {
	TAILQ_ENTRY(fnc_view)	 entries;
	WINDOW			*window;
	PANEL			*panel;
	struct fnc_view		*parent;
	struct fnc_view		*child;
	union {
		struct fnc_diff_view_state	diff;
		struct fnc_tl_view_state	timeline;
		struct fnc_tree_view_state	tree;
		struct fnc_blame_view_state	blame;
		struct fnc_branch_view_state	branch;
	} state;
	enum fnc_view_id	 vid;
	enum fnc_search_state	 search_status;
	enum fnc_search_mvmnt	 searching;
	int			 nlines;
	int			 ncols;
	int			 start_ln;
	int			 start_col;
	int			 lines;	/* Duplicate curses LINES macro. */
	int			 cols;	/* Duplicate curses COLS macro. */
	bool			 focus_child;
	bool			 active; /* Only 1 parent or child at a time. */
	bool			 egress;
	bool			 started_search;
	regex_t			 regex;
	regmatch_t		 regmatch;

	int	(*show)(struct fnc_view *);
	int	(*input)(struct fnc_view **, struct fnc_view *, int);
	int	(*close)(struct fnc_view *);
	int	(*search_init)(struct fnc_view *);
	int	(*search_next)(struct fnc_view *);
};

static volatile sig_atomic_t rec_sigwinch;
static volatile sig_atomic_t rec_sigpipe;
static volatile sig_atomic_t rec_sigcont;

static void		 fnc_show_version(void);
static int		 init_curses(void);
static struct fnc_view	*view_open(int, int, int, int, enum fnc_view_id);
static int		 open_timeline_view(struct fnc_view *, fsl_id_t,
			    const char *);
static int		 view_loop(struct fnc_view *);
static int		 show_timeline_view(struct fnc_view *);
static void		*tl_producer_thread(void *);
static int		 block_main_thread_signals(void);
static int		 build_commits(struct fnc_tl_thread_cx *);
static int		 commit_builder(struct fnc_commit_artifact **, fsl_id_t,
			    fsl_stmt *);
static int		 signal_tl_thread(struct fnc_view *, int);
static int		 draw_commits(struct fnc_view *);
static void		 parse_emailaddr_username(char **);
static int		 formatln(wchar_t **, int *, const char *, int, int);
static int		 multibyte_to_wchar(const char *, wchar_t **, size_t *);
static int		 write_commit_line(struct fnc_view *,
			    struct fnc_commit_artifact *, int);
static int		 view_input(struct fnc_view **, int *,
			    struct fnc_view *, struct view_tailhead *);
static int		 help(struct fnc_view *);
static int		 padpopup(struct fnc_view *, int, int, FILE *,
			    const char *);
static void		 centerprint(WINDOW *, int, int, int, const char *,
			    chtype);
static int		 tl_input_handler(struct fnc_view **, struct fnc_view *,
			    int);
static int		 timeline_scroll_down(struct fnc_view *, int);
static void		 timeline_scroll_up(struct fnc_tl_view_state *, int);
static void		 select_commit(struct fnc_tl_view_state *);
static int		 view_is_parent(struct fnc_view *);
static int		 make_splitscreen(struct fnc_view *);
static int		 make_fullscreen(struct fnc_view *);
static int		 view_split_start_col(int);
static int		 view_search_start(struct fnc_view *);
static int		 tl_search_init(struct fnc_view *);
static int		 tl_search_next(struct fnc_view *);
static bool		 find_commit_match(struct fnc_commit_artifact *,
			    regex_t *);
static int		 init_diff_commit(struct fnc_view **, int,
			    struct fnc_commit_artifact *, struct fnc_view *);
static int		 open_diff_view(struct fnc_view *,
			    struct fnc_commit_artifact *, int, bool, bool, bool,
			    struct fnc_view *, bool,
			    struct fnc_pathlist_head *);
static void		 show_diff_status(struct fnc_view *);
static int		 create_diff(struct fnc_diff_view_state *);
static int		 create_changeset(struct fnc_commit_artifact *);
static int		 write_commit_meta(struct fnc_diff_view_state *);
static int		 wrapline(char *, fsl_size_t ncols_avail,
			    struct fnc_diff_view_state *, off_t *);
static int		 add_line_offset(off_t **, size_t *, off_t);
static int		 diff_commit(fsl_buffer *, struct fnc_commit_artifact *,
			    int, int, int, struct fnc_pathlist_head *);
static int		 diff_checkout(fsl_buffer *, fsl_id_t, int, int, int,
			    struct fnc_pathlist_head *);
static int		 write_diff_meta(fsl_buffer *, const char *,
			    fsl_uuid_str, const char *, fsl_uuid_str, int,
			    enum fsl_ckout_change_e);
static int		 diff_file(fsl_buffer *, fsl_buffer *, const char *,
			    fsl_uuid_str, const char *, enum fsl_ckout_change_e,
			    int, int, bool);
static int		 diff_non_checkin(fsl_buffer *,
			    struct fnc_commit_artifact *, int, int, int);
static int		 diff_file_artifact(fsl_buffer *, fsl_id_t,
			    const fsl_card_F *, fsl_id_t, const fsl_card_F *,
			    fsl_ckout_change_e, int, int, int,
			    enum fnc_diff_type);
static int		 show_diff(struct fnc_view *);
static int		 write_diff(struct fnc_view *, char *);
static int		 match_line(const void *, const void *);
static int		 write_matched_line(int *, const char *, int, int,
			    WINDOW *, regmatch_t *);
static void		 draw_vborder(struct fnc_view *);
static int		 diff_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 set_selected_commit(struct fnc_diff_view_state *,
			    struct commit_entry *);
static int		 diff_search_init(struct fnc_view *);
static int		 diff_search_next(struct fnc_view *);
static int		 view_close(struct fnc_view *);
static int		 map_repo_path(char **);
static bool		 path_is_child(const char *, const char *, size_t);
static int		 path_skip_common_ancestor(char **, const char *,
			    size_t, const char *, size_t);
static bool		 fnc_path_is_root_dir(const char *);
/* static bool		 fnc_path_is_cwd(const char *); */
static int		 fnc_pathlist_insert(struct fnc_pathlist_entry **,
			    struct fnc_pathlist_head *, const char *, void *);
static int		 fnc_path_cmp(const char *, const char *, size_t,
			    size_t);
static void		 fnc_pathlist_free(struct fnc_pathlist_head *);
static int		 browse_commit_tree(struct fnc_view **, int,
			    struct commit_entry *, const char *);
static int		 open_tree_view(struct fnc_view *, const char *,
			    fsl_id_t);
static int		 walk_tree_path(struct fnc_tree_view_state *,
			    struct fnc_repository_tree *,
			    struct fnc_tree_object **, const char *);
static int		 create_repository_tree(struct fnc_repository_tree **,
			    fsl_uuid_str *, fsl_id_t);
static int		 tree_builder(struct fnc_repository_tree *,
			    struct fnc_tree_object **, const char *);
/* static void		 delete_tree_node(struct fnc_tree_entry **, */
/*			    struct fnc_tree_entry *); */
static int		 link_tree_node(struct fnc_repository_tree *,
			    const char *, const char *, fsl_time_t);
static int		 show_tree_view(struct fnc_view *);
static int		 tree_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 blame_tree_entry(struct fnc_view **, int,
			    struct fnc_tree_entry *, struct fnc_parent_trees *,
			    fsl_uuid_str);
static int		 tree_search_init(struct fnc_view *);
static int		 tree_search_next(struct fnc_view *);
static int		 tree_entry_path(char **, struct fnc_parent_trees *,
			    struct fnc_tree_entry *);
static int		 draw_tree(struct fnc_view *, const char *);
static int		 timeline_tree_entry(struct fnc_view **, int,
			    struct fnc_tree_view_state *);
static void		 tree_scroll_up(struct fnc_tree_view_state *, int);
static void		 tree_scroll_down(struct fnc_tree_view_state *, int);
static int		 visit_subtree(struct fnc_tree_view_state *,
			    struct fnc_tree_object *);
static int		 tree_entry_get_symlink_target(char **,
			    struct fnc_tree_entry *);
static int		 match_tree_entry(struct fnc_tree_entry *, regex_t *);
static void		 fnc_object_tree_close(struct fnc_tree_object *);
static void		 fnc_close_repository_tree(struct fnc_repository_tree *);
static int		 open_blame_view(struct fnc_view *, char *,
			    fsl_uuid_str, fsl_id_t, int);
static int		 run_blame(struct fnc_view *);
static int		 fnc_dump_buffer_to_file(off_t *, int *, off_t **,
			    FILE *, fsl_buffer *);
static int		 show_blame_view(struct fnc_view *);
static void		*blame_thread(void *);
static int		 blame_cb(void *, fsl_annotate_opt const * const,
			    fsl_annotate_step const * const);
static int		 draw_blame(struct fnc_view *);
static int		 blame_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 blame_search_init(struct fnc_view *);
static int		 blame_search_next(struct fnc_view *);
static fsl_uuid_cstr	 get_selected_commit_id(struct fnc_blame_line *,
			    int, int, int);
static int		 fnc_commit_qid_alloc(struct fnc_commit_qid **,
			    fsl_uuid_cstr);
static int		 close_blame_view(struct fnc_view *);
static int		 stop_blame(struct fnc_blame *);
static int		 cancel_blame(void *);
static void		 fnc_commit_qid_free(struct fnc_commit_qid *);
static int		 fnc_load_branches(struct fnc_branch_view_state *);
static int		 create_tmp_branchlist_table(void);
static int		 alloc_branch(struct fnc_branch **, const char *,
			    double, bool, bool, bool);
static int		 fnc_branchlist_insert(struct fnc_branchlist_entry **,
			    struct fnc_branchlist_head *, struct fnc_branch *);
static int		 open_branch_view(struct fnc_view *, int, const char *,
			    double, int);
static int		 show_branch_view(struct fnc_view *);
static int		 branch_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 tl_branch_entry(struct fnc_view **, int,
			    struct fnc_branchlist_entry *);
static int		 browse_branch_tree(struct fnc_view **, int,
			    struct fnc_branchlist_entry *);
static void		 branch_scroll_up(struct fnc_branch_view_state *, int);
static void		 branch_scroll_down(struct fnc_branch_view_state *,
			    int);
static int		 branch_search_next(struct fnc_view *);
static int		 branch_search_init(struct fnc_view *);
static int		 match_branchlist_entry(struct fnc_branchlist_entry *,
			    regex_t *);
static int		 close_branch_view(struct fnc_view *);
static void		 fnc_free_branches(struct fnc_branch_view_state *);
static void		 fnc_branch_close(struct fnc_branch *);
static void		 view_set_child(struct fnc_view *, struct fnc_view *);
static int		 view_close_child(struct fnc_view *);
static int		 close_tree_view(struct fnc_view *);
static int		 close_timeline_view(struct fnc_view *);
static int		 close_diff_view(struct fnc_view *);
static int		 view_resize(struct fnc_view *);
static int		 screen_is_split(struct fnc_view *);
static bool		 screen_is_shared(struct fnc_view *);
static void		 fnc_resizeterm(void);
static int		 join_tl_thread(struct fnc_tl_view_state *);
static void		 fnc_free_commits(struct commit_queue *);
static void		 fnc_commit_artifact_close(struct fnc_commit_artifact*);
static int		 fsl_list_object_free(void *, void *);
static void		 sigwinch_handler(int);
static void		 sigpipe_handler(int);
static void		 sigcont_handler(int);
static int		 strtonumcheck(int *, const char *, const int,
			    const int);
static int		 fnc_date_to_mtime(double *, const char *, int);
static char		*fnc_strsep (char **, const char *);
static int		 set_colours(fsl_list *, enum fnc_view_id vid);
static int		 match_colour(const void *, const void *);
static bool		 fnc_home(struct fnc_view *);
static struct fnc_colour	*get_colour(fsl_list *, int);
static struct fnc_tree_entry	*get_tree_entry(struct fnc_tree_object *,
				    int);
static struct fnc_tree_entry	*find_tree_entry(struct fnc_tree_object *,
				    const char *, size_t);

int
main(int argc, const char **argv)
{
	fcli_command	*cmd = NULL;
	char		*path = NULL;
	int		 rc = 0;

	fnc_init.filter_types =
	    (struct artifact_types *)fsl_malloc(sizeof(struct artifact_types));
	fnc_init.filter_types->values = fsl_malloc(sizeof(char *));
	fnc_init.filter_types->nitems = 0;

	if (!setlocale(LC_CTYPE, ""))
		fsl_fprintf(stderr, "[!] Warning: Can't set locale.\n");

	fnc_init.cmdarg = argv[1];	/* Which cmd to show usage if needed. */
	fcli.clientFlags.verbose = 2;	/* Verbose error reporting. */
	fcli.cliFlags = fnc_init.cliflags_global;
	fcli.appHelp = &fnc_init.fnc_help;
	rc = fcli_setup(argc, argv);
	if (rc)
		goto end;

	if (fnc_init.vflag) {
		fnc_show_version();
		goto end;
	} else if (fnc_init.hflag)
		usage();
		/* NOT REACHED */

	rc = fcli_fingerprint_check(true);
	if (rc)
		goto end;

	if (argc == 1)
		cmd = &fnc_init.cmd_args[FNC_VIEW_TIMELINE];
	else {
		rc = fcli_dispatch_commands(fnc_init.cmd_args, false);
		if (rc == FSL_RC_NOT_FOUND && argc == 2) {
			/*
			 * Check if user entered fnc path/in/repo; if valid path
			 * is found, assume fnc timeline path/in/repo was meant.
			 */
			rc = map_repo_path(&path);
			if (rc == FSL_RC_NOT_FOUND || !path) {
				rc = RC(rc,
				    "'%s' is not a valid command or path",
				    argv[1]);
				fnc_init.err = rc;
				usage();
				/* NOT REACHED */
			} else if (rc)
				goto end;
			cmd = &fnc_init.cmd_args[FNC_VIEW_TIMELINE];
			fnc_init.path = path;
			fcli_err_reset(); /* cmd_timeline::fcli_process_flags */
		} else if (rc)
			goto end;
	}

	if ((rc = fcli_has_unused_args(false))) {
		fnc_init.err = rc;
		usage();
		/* NOT REACHED */
	}

	if (!fsl_cx_db_repo(fcli_cx())) {
		rc = RC(FSL_RC_MISUSE, "%s", "repository database required");
		goto end;
	}

	if (cmd != NULL)
		rc = cmd->f(cmd);
end:
	fsl_free(path);
	endwin();
	if (rc) {
		if (rc == FCLI_RC_HELP)
			rc = 0;
		else if (rc == FSL_RC_BREAK) {
			fsl_cx *f = fcli_cx();
			const char *errstr;
			fsl_error_get(&f->error, &errstr, NULL);
			fsl_fprintf(stdout, "%s", errstr);
			fcli_err_reset();  /* For fcli_end_of_main() */
			rc = 0;
		}
	}
	putchar('\n');
	return fcli_end_of_main(rc);
}

static int
cmd_timeline(fcli_command const *argv)
{
	struct fnc_view	*v;
	fsl_cx		*f = fcli_cx();
	fsl_id_t	 rid = -1;
	char		*path = NULL;
	int		 rc = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	if (fnc_init.nrecords.zlimit)
		if ((rc = strtonumcheck(&fnc_init.nrecords.limit,
		    fnc_init.nrecords.zlimit, INT_MIN, INT_MAX)))
			return rc;

	if (fnc_init.sym != NULL) {
		rc = fsl_sym_to_rid(f, fnc_init.sym, FSL_SATYPE_CHECKIN, &rid);
		if (rc || rid < 0)
			return RC(FSL_RC_TYPE,
			    "artifact [%s] not resolvable to a commit",
			    fnc_init.sym);
	}

	if (fnc_init.path)
		path = fsl_strdup(fnc_init.path);
	else
		rc = map_repo_path(&path);
	if (!rc)
		rc = init_curses();
	if (rc)
		goto end;
	v = view_open(0, 0, 0, 0, FNC_VIEW_TIMELINE);
	if (v == NULL) {
		RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}
	rc = open_timeline_view(v, rid, path);
	if (!rc)
		rc = view_loop(v);
end:
	fsl_free(path);
	return rc;
}

/*
 * Look for an in-repository path in **argv. If found, canonicalise it as an
 * absolute path relative to the repository root (e.g., /ckoutdir/found/path),
 * and assign to a dynamically allocated string in *requested_path, which the
 * caller must dispose of with fsl_free or free(3).
 */
static int
map_repo_path(char **requested_path)
{
	fsl_cx		*const f = fcli_cx();
	fsl_buffer	 buf = fsl_buffer_empty;
	char		*canonpath = NULL, *ckoutdir = NULL, *path = NULL;
	const char	*ckoutdir0 = NULL;
	fsl_size_t	 len;
	int		 rc = 0;
	bool		 root;

	*requested_path = NULL;

	/* If no path argument is supplied, default to repository root. */
	if (!fcli_next_arg(false)) {
		*requested_path = fsl_strdup("/");
		if (*requested_path == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		return rc;
	}

	canonpath = fsl_strdup(fcli_next_arg(true));
	if (canonpath == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}

	/*
	 * If no checkout (e.g., 'fnc timeline -R') copy the path verbatim to
	 * check its validity against a deck of F cards in open_timeline_view().
	 */
	ckoutdir0 = fsl_cx_ckout_dir_name(f, &len);
	if (!ckoutdir0) {
		path = fsl_strdup(canonpath);
		goto end;
	}

	path = realpath(canonpath, NULL);
	if (path == NULL && (errno == ENOENT || errno == ENOTDIR)) {
		/* Path is not on disk, assume it is relative to repo root. */
		rc = fsl_file_canonical_name2(ckoutdir0, canonpath, &buf, NULL);
		if (rc) {
			rc = RC(rc, "%s", "fsl_file_canonical_name2");
			goto end;
		}
		fsl_free(path);
		path = realpath(fsl_buffer_cstr(&buf), NULL);
		if (path) {
			/* Confirmed path is relative to repository root. */
			fsl_free(path);
			path = fsl_strdup(canonpath);
			if (path == NULL)
				rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		} else {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_NOT_FOUND),
			    "'%s' not found in tree", canonpath);
			*requested_path = fsl_strdup(canonpath);
		}
		goto end;
	}
	fsl_free(path);
	/*
	 * Use the cwd as the virtual root to canonicalise the supplied path if
	 * it is either: (a) relative; or (b) the root of the current checkout.
	 * Otherwise, use the root of the current checkout.
	 */
	rc = fsl_cx_getcwd(f, &buf);
	if (rc)
		goto end;
	ckoutdir = fsl_mprintf("%.*s", len - 1, ckoutdir0);
	root = fsl_strcmp(ckoutdir, fsl_buffer_cstr(&buf)) == 0;
	fsl_buffer_reuse(&buf);
	rc = fsl_ckout_filename_check(f, (canonpath[0] == '.' || !root) ?
	    true : false, canonpath, &buf);
	if (rc)
		goto end;
	fsl_free(canonpath);
	canonpath = fsl_strdup(fsl_buffer_str(&buf));

	if (canonpath[0] == '\0') {
		path = fsl_strdup(canonpath);
		if (path == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else {
		fsl_buffer_reuse(&buf);
		rc = fsl_file_canonical_name2(f->ckout.dir, canonpath, &buf,
		    false);
		if (rc)
			goto end;
		path = fsl_strdup(fsl_buffer_str(&buf));
		if (path == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		if (access(path, F_OK) != 0) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
			    "path does not exist or inaccessible [%s]", path);
			goto end;
		}
		/*
		 * Now we have an absolute path, check again if it's the ckout
		 * dir; if so, clear it to signal an open_timeline_view() check.
		 */
		len = fsl_strlen(path);
		if (!fsl_strcmp(path, f->ckout.dir)) {
			fsl_free(path);
			path = fsl_strdup("");
			if (path == NULL) {
				rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
				goto end;
			}
		} else if (len > f->ckout.dirLen && path_is_child(path,
		    f->ckout.dir, f->ckout.dirLen)) {
			char *child;
			/*
			 * Matched on-disk path within the repository; strip
			 * common prefix with repository root path.
			 */
			rc = path_skip_common_ancestor(&child, f->ckout.dir,
			    f->ckout.dirLen, path, len);
			if (rc)
				goto end;
			fsl_free(path);
			path = child;
		} else {
			/*
			 * Matched on-disk path outside the repository; treat
			 * as relative to repo root. (Though this should fail.)
			 */
			fsl_free(path);
			path = canonpath;
			canonpath = NULL;
		}
	}

	/* Trim trailing slash if it exists. */
	if (path[fsl_strlen(path) - 1] == '/')
		path[fsl_strlen(path) - 1] = '\0';

end:
	fsl_buffer_clear(&buf);
	fsl_free(canonpath);
	fsl_free(ckoutdir);
	if (rc)
		fsl_free(path);
	else {
		/* Make path absolute from repository root. */
		if (path[0] != '/' && (path[0] != '.' && path[1] != '/')) {
			char *abspath;
			if ((abspath = fsl_mprintf("/%s", path)) == NULL) {
				rc = RC(FSL_RC_ERROR, "%s", "fsl_mprintf");
				goto end;
			}
			fsl_free(path);
			path = abspath;
		}

		*requested_path = path;
	}
	return rc;
}

static bool
path_is_child(const char *child, const char *parent, size_t parentlen)
{
	if (parentlen == 0 || fnc_path_is_root_dir(parent))
		return true;

	if (fsl_strncmp(parent, child, parentlen) != 0)
		return false;
	if (child[parentlen - 1 /* Trailing slash */] != '/')
		return false;

	return true;
}

/*
 * As a special case, due to fsl_ckout_filename_check() resolving the current
 * checkout directory to ".", this function returns true for ".". For this
 * reason, when path is intended to be the current working directory for any
 * directory other than the repository root, callers must ensure path is either
 * absolute or relative to the respository root--not ".".
 */
static bool
fnc_path_is_root_dir(const char *path)
{
	while (*path == '/' || *path == '.')
		++path;
	return (*path == '\0');
}

static int
path_skip_common_ancestor(char **child, const char *parent_abspath,
    size_t parentlen, const char *abspath, size_t len)
{
	size_t	bufsz;
	int	rc = 0;

	*child = NULL;

	if (parentlen >= len)
		return RC(FSL_RC_RANGE, "invalid path [%s]", abspath);
	if (fsl_strncmp(parent_abspath, abspath, parentlen) != 0)
		return RC(FSL_RC_TYPE, "invalid path [%s]", abspath);
	if (!fnc_path_is_root_dir(parent_abspath) &&
	    abspath[parentlen - 1 /* Trailing slash */] != '/')
		return RC(FSL_RC_TYPE, "invalid path [%s]", abspath);
	while (abspath[parentlen] == '/')
		++abspath;
	bufsz = len - parentlen + 1;
	*child = fsl_malloc(bufsz);
	if (*child == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	if (strlcpy(*child, abspath + parentlen, bufsz) >= bufsz) {
		rc = RC(FSL_RC_RANGE, "%s", "strlcpy");
		fsl_free(*child);
		*child = NULL;
	}
	return rc;
}

#if 0
static bool
fnc_path_is_cwd(const char *path)
{
	return (path[0] == '.' && path[1] == '\0');
}
#endif

static int
init_curses(void)
{
	initscr();
	cbreak();
	noecho();
	nonl();
	intrflush(stdscr, FALSE);
	keypad(stdscr, TRUE);
	curs_set(0);
	set_escdelay(0);  /* ESC should return immediately. */
#ifndef __linux__
	typeahead(-1);	/* Don't disrupt screen update operations. */
#endif

	if (!fnc_init.nocolour && has_colors()) {
		start_color();
		use_default_colors();
	}

	if (sigaction(SIGPIPE, &(struct sigaction){{sigpipe_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "sigaction(SIGPIPE)");
	if (sigaction(SIGWINCH, &(struct sigaction){{sigwinch_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "sigaction(SIGWINCH)");
	if (sigaction(SIGCONT, &(struct sigaction){{sigcont_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "sigaction(SIGCONT)");

	return 0;
}

static struct fnc_view *
view_open(int nlines, int ncols, int start_ln, int start_col,
    enum fnc_view_id vid)
{
	struct fnc_view *view = calloc(1, sizeof(*view));

	if (view == NULL)
		return NULL;

	view->vid = vid;
	view->lines = LINES;
	view->cols = COLS;
	view->nlines = nlines ? nlines : LINES - start_ln;
	view->ncols = ncols ? ncols : COLS - start_col;
	view->start_ln = start_ln;
	view->start_col = start_col;
	view->window = newwin(nlines, ncols, start_ln, start_col);
	if (view->window == NULL) {
		view_close(view);
		return NULL;
	}
	view->panel = new_panel(view->window);
	if (view->panel == NULL || set_panel_userptr(view->panel, view) != OK) {
		view_close(view);
		return NULL;
	}

	keypad(view->window, TRUE);
	return view;
}

static int
open_timeline_view(struct fnc_view *view, fsl_id_t rid, const char *path)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	fsl_cx				*f = fcli_cx();
	fsl_db				*db = fsl_cx_db_repo(f);
	fsl_buffer			 sql = fsl_buffer_empty;
	char				*startdate = NULL;
	fsl_id_t			 idtag = 0;
	int				 idx, rc = 0;

	if (path != s->path) {
		fsl_free(s->path);
		s->path = fsl_strdup(path);
		if (s->path == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	}

	/*
	 * TODO: See about opening this API.
	 * If a path has been supplied, create a table of all path's
	 * ancestors and add "AND blob.rid IN fsl_computed_ancestors" to query.
	 */
	/* if (path[1]) { */
	/*	rc = fsl_compute_ancestors(db, rid, 0, 0); */
	/*	if (rc) */
	/*		return RC(FSL_RC_DB, "%s", "fsl_compute_ancestors"); */
	/* } */
	s->thread_cx.q = NULL;
	/* s->selected_idx = 0; */	/* Unnecessary? */

	TAILQ_INIT(&s->commits.head);
	s->commits.ncommits = 0;

	if (rid != -1)
		startdate = fsl_mprintf("(SELECT mtime FROM event "
		    "WHERE objid=%d)", rid);
	else
		fsl_ckout_version_info(f, NULL, &s->curr_ckout_uuid);

	/*
	 * In 'fnc timeline -R repo.fossil path' case, check that path is a
	 * valid repository path in the repository tree as at either the
	 * latest check-in or the specified commit.
	 */
	if (s->curr_ckout_uuid == NULL && path[1]) {
		fsl_deck d = fsl_deck_empty;
		bool ispath = false;
		rc = fsl_deck_load_sym(f, &d, fnc_init.sym ? fnc_init.sym :
		    "tip", FSL_SATYPE_CHECKIN);
		fsl_deck_F_rewind(&d);
		if (fsl_deck_F_search(&d, path + 1 /* Slash */) == NULL) {
			const fsl_card_F *cf;
			fsl_deck_F_next(&d, &cf);
			do {
				fsl_deck_F_next(&d, &cf);
				if (cf && !fsl_strncmp(path + 1 /* Slash */,
				    cf->name, fsl_strlen(path) - 1)) {
					ispath = true;
					break;
				}
			} while (cf);
		} else
			ispath = true;
		fsl_deck_finalize(&d);
		if (!ispath)
			return RC(FSL_RC_NOT_FOUND, "'%s' invalid path in [%s]",
			    path + 1, fnc_init.sym ? fnc_init.sym : "tip");
	}

	if ((rc = pthread_cond_init(&s->thread_cx.commit_consumer, NULL))) {
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_init");
		goto end;
	}
	if ((rc = pthread_cond_init(&s->thread_cx.commit_producer, NULL))) {
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_init");
		goto end;
	}

	fsl_buffer_appendf(&sql, "SELECT "
            /* 0 */"uuid, "
	    /* 1 */"datetime(event.mtime%s), "
	    /* 2 */"coalesce(euser, user), "
	    /* 3 */"rid AS rid, "
	    /* 4 */"event.type AS eventtype, "
	    /* 5 */"(SELECT group_concat(substr(tagname,5), ',') "
	    "FROM tag, tagxref WHERE tagname GLOB 'sym-*' "
	    "AND tag.tagid=tagxref.tagid AND tagxref.rid=blob.rid "
	    "AND tagxref.tagtype > 0) as tags, "
	    /*6*/"coalesce(ecomment, comment) AS comment FROM event JOIN blob "
	    "WHERE blob.rid=event.objid", fnc_init.utc ? "" : ", 'localtime'");

	if (fnc_init.filter_types->nitems) {
		fsl_buffer_appendf(&sql, " AND (");
		for (idx = 0; idx < fnc_init.filter_types->nitems; ++idx) {
			fsl_buffer_appendf(&sql, " eventtype=%Q%s",
			    fnc_init.filter_types->values[idx], (idx + 1) <
			    fnc_init.filter_types->nitems ? " OR " : ")");
			/* This produces a double-free? */
			/* fsl_free((char *)fnc_init.filter_types->values[idx]); */
			fnc_init.filter_types->values[idx] = NULL;
		}
		fsl_free(fnc_init.filter_types->values);
		fsl_free(fnc_init.filter_types);
	}

	if (fnc_init.filter_branch) {
		idtag = fsl_db_g_id(db, 0,
                    "SELECT tagid FROM tag WHERE tagname='sym-%q'",
                    fnc_init.filter_branch);
		if (idtag > 0)
			fsl_buffer_appendf(&sql,
                             " AND EXISTS(SELECT 1 FROM tagxref"
                             " WHERE tagid=%"FSL_ID_T_PFMT
                             " AND tagtype > 0 AND rid=blob.rid)", idtag);
		else {
			rc = RC(FSL_RC_NOT_FOUND, "Invalid branch name [%s]",
			    fnc_init.filter_branch);
			goto end;
		}
	}

	if (fnc_init.filter_tag) {
		idtag = fsl_db_g_id(db, 0,
                    "SELECT tagid FROM tag WHERE tagname GLOB 'sym-%q'",
                    fnc_init.filter_tag);
                if (idtag == 0)
			idtag = fsl_db_g_id(db, 0,
			    "SELECT tagid FROM tag WHERE tagname='%q'",
			    fnc_init.filter_tag);
		if (idtag > 0)
			fsl_buffer_appendf(&sql,
                             " AND EXISTS(SELECT 1 FROM tagxref"
                             " WHERE tagid=%"FSL_ID_T_PFMT
                             " AND tagtype > 0 AND rid=blob.rid)", idtag);
		else {
			rc = RC(FSL_RC_NOT_FOUND, "Invalid tag [%s]",
			    fnc_init.filter_tag);
			goto end;
		}
	}

	if (fnc_init.filter_user)
		if ((rc = fsl_buffer_appendf(&sql,
                    " AND coalesce(euser, user) GLOB lower('*%q*')",
                    fnc_init.filter_user)))
		goto end;

	if (startdate) {
		fsl_buffer_appendf(&sql, " AND event.mtime <= %s", startdate);
		fsl_free(startdate);
	}

	/*
	 * If path is not root ("/"), a versioned path in the repository has
	 * been requested, only retrieve commits involving path.
	 */
	if (path[1]) {
		fsl_buffer_appendf(&sql,
		    " AND EXISTS(SELECT 1 FROM mlink"
		    " WHERE mlink.mid = event.objid"
		    " AND mlink.fnid IN ");
		if (fsl_cx_is_case_sensitive(f)) {
			fsl_buffer_appendf(&sql,
			    "(SELECT fnid FROM filename"
			    " WHERE name = %Q OR name GLOB '%q/*')",
			    path + 1, path + 1);  /* Skip prepended slash. */
		} else {
			fsl_buffer_appendf(&sql,
			    "(SELECT fnid FROM filename"
			    " WHERE name = %Q COLLATE nocase"
			    " OR lower(name) GLOB lower('%q/*'))",
			    path + 1, path + 1);  /* Skip prepended slash. */
		}
		fsl_buffer_append(&sql, ")", 1);
	}

	fsl_buffer_appendf(&sql, " ORDER BY event.mtime DESC");

	if (fnc_init.nrecords.limit > 0)
		fsl_buffer_appendf(&sql, " LIMIT %d", fnc_init.nrecords.limit);

	view->show = show_timeline_view;
	view->input = tl_input_handler;
	view->close = close_timeline_view;
	view->search_init = tl_search_init;
	view->search_next = tl_search_next;

	s->thread_cx.q = fsl_stmt_malloc();
	rc = fsl_db_prepare(db, s->thread_cx.q, "%b", &sql);
	if (rc) {
		rc = RC(rc, "%s", "fsl_db_prepare");
		goto end;
	}
	rc = fsl_stmt_step(s->thread_cx.q);
	if (rc) {
		switch (rc) {
		case FSL_RC_STEP_ROW:
			rc = 0;
			break;
		case FSL_RC_STEP_ERROR:
			rc = RC(rc, "%s", "fsl_stmt_step");
			goto end;
		case FSL_RC_STEP_DONE:
			rc = RC(FSL_RC_BREAK, "%s", "no matching records");
			goto end;
		}
	}

	s->colour = !fnc_init.nocolour && has_colors();
	s->thread_cx.rc = 0;
	s->thread_cx.db = db;
	s->thread_cx.spin_idx = 0;
	s->thread_cx.ncommits_needed = view->nlines - 1;
	s->thread_cx.commits = &s->commits;
	s->thread_cx.timeline_end = false;
	s->thread_cx.quit = &s->quit;
	s->thread_cx.first_commit_onscreen = &s->first_commit_onscreen;
	s->thread_cx.selected_commit = &s->selected_commit;
	s->thread_cx.searching = &view->searching;
	s->thread_cx.search_status = &view->search_status;
	s->thread_cx.regex = &view->regex;
	s->thread_cx.path = s->path;

	if (s->colour)
		set_colours(&s->colours, FNC_VIEW_TIMELINE);
end:
	fsl_buffer_clear(&sql);
	if (rc) {
		close_timeline_view(view);
		if (db->error.code)
			rc = fsl_cx_uplift_db_error(f, db);
	}
	return rc;
}

static int
view_loop(struct fnc_view *view)
{
	struct view_tailhead	 views;
	struct fnc_view		*new_view;
	int			 done = 0, err = 0, rc = 0;

	if ((rc = pthread_mutex_lock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	TAILQ_INIT(&views);
	TAILQ_INSERT_HEAD(&views, view, entries);

	view->active = true;
	rc = view->show(view);
	if (rc)
		return rc;

	while (!TAILQ_EMPTY(&views) && !done && !rec_sigpipe) {
		rc = view_input(&new_view, &done, view, &views);
		if (rc)
			break;
		if (view->egress) {
			struct fnc_view *v, *prev = NULL;

			if (view_is_parent(view))
				prev = TAILQ_PREV(view, view_tailhead, entries);
			else if (view->parent)
				prev = view->parent;

			if (view->parent) {
				view->parent->child = NULL;
				view->parent->focus_child = false;
			} else
				TAILQ_REMOVE(&views, view, entries);

			rc = view_close(view);
			if (rc)
				goto end;

			view = NULL;
			TAILQ_FOREACH(v, &views, entries) {
				if (v->active)
					break;
			}
			if (view == NULL && new_view == NULL) {
				/* No view is active; try to pick one. */
				if (prev)
					view = prev;
				else if (!TAILQ_EMPTY(&views))
					view = TAILQ_LAST(&views,
					    view_tailhead);
				if (view) {
					if (view->focus_child) {
						view->child->active = true;
						view = view->child;
					} else
						view->active = true;
				}
			}
		}
		if (new_view) {
			struct fnc_view *v, *t;
			/* Allow only one parent view per type. */
			TAILQ_FOREACH_SAFE(v, &views, entries, t) {
				if (v->vid != new_view->vid)
					continue;
				TAILQ_REMOVE(&views, v, entries);
				rc = view_close(v);
				if (rc)
					goto end;
				break;
			}
			TAILQ_INSERT_TAIL(&views, new_view, entries);
			view = new_view;
		}
		if (view) {
			if (view_is_parent(view)) {
				if (view->child && view->child->active)
					view = view->child;
			} else {
				if (view->parent && view->parent->active)
					view = view->parent;
			}
			show_panel(view->panel);
			if (view->child && screen_is_split(view->child))
				show_panel(view->child->panel);
			if (view->parent && screen_is_split(view)) {
				rc = view->parent->show(view->parent);
				if (rc)
					goto end;
			}
			rc = view->show(view);
			if (rc)
				goto end;
			if (view->child) {
				rc = view->child->show(view->child);
#ifdef __linux__
				wnoutrefresh(view->child->window);
#endif
				if (rc)
					goto end;
			}
#ifdef __linux__
			wnoutrefresh(view->window);
#else
			update_panels();
#endif
			doupdate();
		}
	}
end:
	while (!TAILQ_EMPTY(&views)) {
		view = TAILQ_FIRST(&views);
		TAILQ_REMOVE(&views, view, entries);
		view_close(view);
	}

	if ((err = pthread_mutex_unlock(&fnc_mutex)) && !rc)
		rc = RC(fsl_errno_to_rc(err, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");

	return rc;
}

static int
show_timeline_view(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	int				 rc = 0;

	if (!s->thread_id) {
		rc = pthread_create(&s->thread_id, NULL, tl_producer_thread,
		    &s->thread_cx);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_create");
		if (s->thread_cx.ncommits_needed > 0) {
			rc = signal_tl_thread(view, 1);
			if (rc)
				return rc;
		}
	}

	return draw_commits(view);
}

static void *
tl_producer_thread(void *state)
{
	struct fnc_tl_thread_cx	*cx = state;
	int			 rc;
	bool			 done = false;

	rc = block_main_thread_signals();
	if (rc)
		return (void *)(intptr_t)rc;

	while (!done && !rc && !rec_sigpipe) {
		switch (rc = build_commits(cx)) {
		case FSL_RC_STEP_DONE:
			done = true;
			/* FALL THROUGH */
		case FSL_RC_STEP_ROW:
			rc = 0;
			/* FALL THROUGH */
		default:
			if (rc) {
				cx->rc = rc;
				return (void *)(intptr_t)rc;
			}
			else if (cx->ncommits_needed > 0)
				cx->ncommits_needed--;
			break;
		}

		if ((rc = pthread_mutex_lock(&fnc_mutex))) {
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
			break;
		} else if (*cx->first_commit_onscreen == NULL) {
			*cx->first_commit_onscreen =
			    TAILQ_FIRST(&cx->commits->head);
			*cx->selected_commit = *cx->first_commit_onscreen;
		} else if (*cx->quit)
			done = true;

		if ((rc = pthread_cond_signal(&cx->commit_producer))) {
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_cond_signal");
			pthread_mutex_unlock(&fnc_mutex);
			break;
		}

		if (done)
			cx->ncommits_needed = 0;
		else if (cx->ncommits_needed == 0) {
			if ((rc = pthread_cond_wait(&cx->commit_consumer,
			    &fnc_mutex)))
				rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
				    "%s", "pthread_cond_wait");
			if (*cx->quit)
				done = true;
		}

		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
	}

	cx->timeline_end = true;
	return (void *)(intptr_t)rc;
}

static int
block_main_thread_signals(void)
{
	sigset_t	 set;

	if (sigemptyset(&set) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigemptyset");

	/* Bespoke signal handlers for SIGWINCH and SIGCONT. */
	if (sigaddset(&set, SIGWINCH) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigaddset");
	if (sigaddset(&set, SIGCONT) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigaddset");

	/* ncurses handles SIGTSTP. */
	if (sigaddset(&set, SIGTSTP) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigaddset");

	if (pthread_sigmask(SIG_BLOCK, &set, NULL))
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "pthread_sigmask");

	return 0;
}

static int
build_commits(struct fnc_tl_thread_cx *cx)
{
	int		 rc = 0;

	if (cx->tree_open) {
		/*
		 * XXX If a tree has been opened with the 't' key binding, the
		 * commit builder statement needs to be reset otherwise one of
		 * the SQLite3 APIs down the fsl_stmt_step() call stack fails,
		 * irrespective of whether fsl_db_prepare_cached() is called.
		 */
		fsl_size_t loaded = cx->q->rowCount;
		cx->tree_open = false;
		rc = fsl_stmt_reset(cx->q);
		if (rc)
			return RC(rc, "%s", "fsl_stmt_reset");
		while (loaded--)
			if ((rc = fsl_stmt_step(cx->q)) != FSL_RC_STEP_ROW)
				return RC(rc, "%s", "fsl_stmt_step");
	}
	/*
	 * Step through the given SQL query, passing each row to the commit
	 * builder to build commits for the timeline.
	 */
	do {
		struct fnc_commit_artifact	*commit = NULL;
		struct commit_entry		*dup_entry, *entry;

		rc = commit_builder(&commit, 0, cx->q);
		if (rc)
			return RC(rc, "%s", "commit_builder");
		/*
		 * TODO: Find out why, without this, fnc reads and displays
		 * the first (i.e., latest) commit twice. This hack checks to
		 * see if the current row returned a UUID matching the last
		 * commit added to the list to avoid adding a duplicate entry.
		 */
		dup_entry = TAILQ_FIRST(&cx->commits->head);
		if (cx->commits->ncommits == 1 &&
		    !fsl_strcmp(dup_entry->commit->uuid, commit->uuid)) {
			fnc_commit_artifact_close(commit);
			cx->ncommits_needed++;
			continue;
		}

		entry = fsl_malloc(sizeof(*entry));
		if (entry == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_malloc");

		entry->commit = commit;

		rc = pthread_mutex_lock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");

		entry->idx = cx->commits->ncommits;
		TAILQ_INSERT_TAIL(&cx->commits->head, entry, entries);
		cx->commits->ncommits++;

		if (!cx->endjmp && *cx->searching == SEARCH_FORWARD &&
		    *cx->search_status == SEARCH_WAITING) {
			if (find_commit_match(commit, cx->regex))
				*cx->search_status = SEARCH_CONTINUE;
		}

		rc = pthread_mutex_unlock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");

	} while ((rc = fsl_stmt_step(cx->q)) == FSL_RC_STEP_ROW
	    && *cx->searching == SEARCH_FORWARD
	    && *cx->search_status == SEARCH_WAITING);

	return rc;
}

/*
 * Given prepared SQL statement q _XOR_ record ID rid, allocate and build the
 * corresponding commit artifact from the result set. The commit must
 * eventually be disposed of with fnc_commit_artifact_close().
 */
static int
commit_builder(struct fnc_commit_artifact **ptr, fsl_id_t rid, fsl_stmt *q)
{
	fsl_cx				*f = fcli_cx();
	fsl_db				*db = fsl_needs_repo(f);
	struct fnc_commit_artifact	*commit = NULL;
	fsl_buffer			 buf = fsl_buffer_empty;
	const char			*comment, *prefix, *type;
	int				 rc = 0;
	enum fnc_diff_type		 diff_type = FNC_DIFF_WIKI;

	if (rid) {
		rc = fsl_db_prepare(db, q, "SELECT "
		    /* 0 */"uuid, "
		    /* 1 */"datetime(event.mtime%s), "
		    /* 2 */"coalesce(euser, user), "
		    /* 3 */"rid AS rid, "
		    /* 4 */"event.type AS eventtype, "
		    /* 5 */"(SELECT group_concat(substr(tagname,5), ',') "
		    "FROM tag, tagxref WHERE tagname GLOB 'sym-*' "
		    "AND tag.tagid=tagxref.tagid AND tagxref.rid=blob.rid "
		    "AND tagxref.tagtype > 0) as tags, "
		    /*6*/"coalesce(ecomment, comment) AS comment "
		    "FROM event JOIN blob WHERE blob.rid=%d AND event.objid=%d",
		    fnc_init.utc ? "" : ", 'localtime'", rid, rid);
		if (rc)
			return RC(FSL_RC_DB, "%s", "fsl_db_prepare");
		fsl_stmt_step(q);
	}

	type = fsl_stmt_g_text(q, 4, NULL);
	comment = fsl_stmt_g_text(q, 6, NULL);
	prefix = NULL;

	switch (*type) {
	case 'c':
		type = "checkin";
		diff_type = FNC_DIFF_COMMIT;
		break;
	case 'w':
		type = "wiki";
		if (comment) {
			switch (*comment) {
			case '+':
				prefix = "Added: ";
				++comment;
				break;
			case '-':
				prefix = "Deleted: ";
				++comment;
				break;
			case ':':
				prefix = "Edited: ";
				++comment;
				break;
			default:
				break;
			}
			if (prefix)
				rc = fsl_buffer_append(&buf, prefix, -1);
		}
		break;
	case 'g':
		type = "tag";
		break;
	case 'e':
		type = "technote";
		break;
	case 't':
		type = "ticket";
		break;
	case 'f':
		type = "forum";
		break;
	};
	if (!rc && comment)
		rc = fsl_buffer_append(&buf, comment, -1);
	if (rc) {
		rc = RC(rc, "%s", "fsl_buffer_append");
		goto end;
	}

	commit = calloc(1, sizeof(*commit));
	if (commit == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
		goto end;
	}

	if (!rid && (rc = fsl_stmt_get_id(q, 3, &rid))) {
		rc = RC(rc, "%s", "fsl_stmt_get_id");
		goto end;
	}
	/* Is there a more efficient way to get the parent? */
	commit->puuid = fsl_db_g_text(db, NULL,
	    "SELECT uuid FROM plink, blob WHERE plink.cid=%d "
	    "AND blob.rid=plink.pid AND plink.isprim", rid);
	commit->prid = fsl_uuid_to_rid(f, commit->puuid);
	commit->uuid = fsl_strdup(fsl_stmt_g_text(q, 0, NULL));
	commit->rid = rid;
	commit->type = fsl_strdup(type);
	commit->diff_type = diff_type;
	commit->timestamp = fsl_strdup(fsl_stmt_g_text(q, 1, NULL));
	commit->user = fsl_strdup(fsl_stmt_g_text(q, 2, NULL));
	commit->branch = fsl_strdup(fsl_stmt_g_text(q, 5, NULL));
	commit->comment = fsl_strdup(comment ? fsl_buffer_str(&buf) : "");
	fsl_buffer_clear(&buf);

	*ptr = commit;
end:
	return rc;
}

static int
signal_tl_thread(struct fnc_view *view, int wait)
{
	struct fnc_tl_thread_cx	*cx = &view->state.timeline.thread_cx;
	int			 rc = 0;

	while (cx->ncommits_needed > 0) {
		if (cx->timeline_end)
			break;

		/* Wake timeline thread. */
		if ((rc = pthread_cond_signal(&cx->commit_consumer)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_cond_signal");

		/*
		 * Mutex will be released while view_loop().view_input() waits
		 * in wgetch(), at which point the timeline thread will run.
		 */
		if (!wait)
			break;

		/* Show status update in timeline view. */
		show_timeline_view(view);
		update_panels();
		doupdate();

		/* Wait while the next commit is being loaded. */
		if ((rc = pthread_cond_wait(&cx->commit_producer, &fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_cond_wait");

		/* Show status update in timeline view. */
		show_timeline_view(view);
		update_panels();
		doupdate();
	}

	return cx->rc;
}

static int
draw_commits(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fnc_tl_thread_cx		*tcx = &s->thread_cx;
	struct commit_entry		*entry = s->selected_commit;
	struct fnc_colour		*c = NULL;
	const char			*search_str = NULL;
	char				*headln = NULL, *idxstr = NULL;
	char				*branch = NULL, *type = NULL;
	char				*uuid = NULL;
	wchar_t				*wcstr;
	int				 ncommits = 0, rc = 0, wstrlen = 0;
	int				 ncols_needed, max_usrlen = -1;

	if (s->selected_commit && !(view->searching != SEARCH_DONE &&
	    view->search_status == SEARCH_WAITING)) {
		uuid = fsl_strdup(s->selected_commit->commit->uuid);
		branch = fsl_strdup(s->selected_commit->commit->branch);
		type = fsl_strdup(s->selected_commit->commit->type);
	}

	if (s->thread_cx.ncommits_needed > 0) {
		if ((idxstr = fsl_mprintf(" [%d/%d] %s",
		    entry ? entry->idx + 1 : 0, s->commits.ncommits,
		    (view->searching && !view->search_status) ?
		    "searching..." : "loading...")) == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			goto end;
		}
	} else {
		if (view->searching) {
			if (view->search_status == SEARCH_COMPLETE)
				search_str = "no more matches";
			else if (view->search_status == SEARCH_NO_MATCH)
				search_str = "no matches found";
			else if (view->search_status == SEARCH_WAITING)
				search_str = "searching...";
		}

		if ((idxstr = fsl_mprintf("%s [%d/%d] %s",
		    !fsl_strcmp(uuid, s->curr_ckout_uuid) ? " [current]" : "",
		    entry ? entry->idx + 1 : 0, s->commits.ncommits,
		    search_str ? search_str : (branch ? branch : "")))
		    == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			goto end;
		}
	}
	/*
	 * Compute cols needed to fit all components of the headline to truncate
	 * the hash component if needed. wiki, tag, and ticket artifacts don't
	 * have a branch component, checkins and some technotes do, so add a col
	 * for the space separator. Same applies if search_str is being shown.
	 */
	ncols_needed = fsl_strlen(type) + fsl_strlen(idxstr) + FSL_STRLEN_K256
	    + (!search_str && (!fsl_strcmp(type, "wiki") ||
	    !fsl_strcmp(type, "tag")  || !fsl_strcmp(type, "ticket") ||
	    (!branch && !fsl_strcmp(type, "technote"))) ? 0 : 1);
	/* If a path has been requested, display it in the headline. */
	if (s->path[1]) {
		if ((headln = fsl_mprintf("%s%c%.*s %s%s", type ? type : "",
		    type ? ' ' : SPINNER[tcx->spin_idx], view->ncols <
		    ncols_needed ? view->ncols - (ncols_needed -
		    FSL_STRLEN_K256) : FSL_STRLEN_K256, uuid ? uuid :
		    "........................................",
		    s->path, idxstr)) == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			headln = NULL;
			goto end;
		}
	} else if ((headln = fsl_mprintf("%s%c%.*s%s", type ? type : "", type ?
	    ' ' : SPINNER[tcx->spin_idx], view->ncols < ncols_needed ?
	    view->ncols - (ncols_needed - FSL_STRLEN_K256) : FSL_STRLEN_K256,
	    uuid ? uuid : "........................................", idxstr))
	    == NULL) {
		rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		headln = NULL;
		goto end;
	}
	if (SPINNER[++tcx->spin_idx] == '\0')
		tcx->spin_idx = 0;
	rc = formatln(&wcstr, &wstrlen, headln, view->ncols, 0);
	if (rc)
		goto end;

	werase(view->window);

	if (screen_is_shared(view))
		wstandout(view->window);
	if (s->colour)
		c = get_colour(&s->colours, FNC_COMMIT_ID);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, wcstr);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	while (wstrlen < view->ncols) {
		waddch(view->window, ' ');
		++wstrlen;
	}
	if (screen_is_shared(view))
		wstandend(view->window);
	fsl_free(wcstr);
	if (view->nlines <= 1)
		goto end;

	/* Parse commits to be written on screen for the longest username. */
	entry = s->first_commit_onscreen;
	while (entry) {
		wchar_t		*usr_wcstr;
		char		*user;
		int		 usrlen;
		if (ncommits >= view->nlines - 1)
			break;
		user = fsl_strdup(entry->commit->user);
		if (user == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		if (strpbrk(user, "<@>") != NULL)
			parse_emailaddr_username(&user);
		rc = formatln(&usr_wcstr, &usrlen, user, view->ncols, 0);
		if (max_usrlen < usrlen)
			max_usrlen = usrlen;
		fsl_free(usr_wcstr);
		fsl_free(user);
		++ncommits;
		entry = TAILQ_NEXT(entry, entries);
	}

	ncommits = 0;
	entry = s->first_commit_onscreen;
	s->last_commit_onscreen = s->first_commit_onscreen;
	while (entry) {
		if (ncommits >= view->nlines - 1)
			break;
		if (ncommits == s->selected_idx)
			wattr_on(view->window, A_REVERSE, NULL);
		rc = write_commit_line(view, entry->commit, max_usrlen);
		if (ncommits == s->selected_idx)
			wattr_off(view->window, A_REVERSE, NULL);
		++ncommits;
		s->last_commit_onscreen = entry;
		entry = TAILQ_NEXT(entry, entries);
	}
	draw_vborder(view);

end:
	free(branch);
	free(type);
	free(uuid);
	free(idxstr);
	free(headln);
	return rc;
}

static void
parse_emailaddr_username(char **username)
{
	char	*lt, *usr;

	lt = strchr(*username, '<');
	if (lt && lt[1] != '\0') {
		usr = fsl_strdup(++lt);
		fsl_free(*username);
	} else
		usr = *username;
	usr[strcspn(usr, "@>")] = '\0';

	*username = usr;
}

static int
formatln(wchar_t **ptr, int *wstrlen, const char *mbstr, int column_limit,
    int start_column)
{
	wchar_t		*wline = NULL;
	size_t		 i, wlen;
	int		 rc = 0, cols = 0;

	*ptr = NULL;
	*wstrlen = 0;

	rc = multibyte_to_wchar(mbstr, &wline, &wlen);
	if (rc)
		return rc;

	if (wlen > 0 && wline[wlen - 1] == L'\n') {
		wline[wlen - 1] = L'\0';
		wlen--;
	}
	if (wlen > 0 && wline[wlen - 1] == L'\r') {
		wline[wlen - 1] = L'\0';
		wlen--;
	}

	i = 0;
	while (i < wlen) {
		int width = wcwidth(wline[i]);

		if (width == 0) {
			i++;
			continue;
		}

		if (width == 1 || width == 2) {
			if (cols + width > column_limit)
				break;
			cols += width;
			i++;
		} else if (width == -1) {
			if (wline[i] == L'\t') {
				width = TABSIZE -
				    ((cols + column_limit) % TABSIZE);
			} else {
				width = 1;
				wline[i] = L'.';
			}
			if (cols + width > column_limit)
				break;
			cols += width;
			i++;
		} else {
			rc = RC(FSL_RC_RANGE, "%s", "wcwidth");
			goto end;
		}
	}
	wline[i] = L'\0';
	if (wstrlen)
		*wstrlen = cols;
end:
	if (rc)
		free(wline);
	else
		*ptr = wline;
	return rc;
}

static int
multibyte_to_wchar(const char *src, wchar_t **dst, size_t *dstlen)
{
	int	rc = 0;

	/*
	 * mbstowcs POSIX extension specifies that the number of wchar that
	 * would be written are returned when first arg is a null pointer:
	 * https://en.cppreference.com/w/cpp/string/multibyte/mbstowcs
	 */
	*dstlen = mbstowcs(NULL, src, 0);
	if (*dstlen == (size_t)-1) {
		if (errno == EILSEQ)
			return RC(FSL_RC_RANGE,
			    "invalid multibyte character [%s]", src);
		return RC(FSL_RC_MISUSE, "mbstowcs(%s)", src);
	}


	*dst = NULL;
	*dst = fsl_malloc(sizeof(wchar_t) * (*dstlen + 1));
	if (*dst == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "malloc");
		goto end;
	}

	if (mbstowcs(*dst, src, *dstlen) != *dstlen)
		rc = RC(FSL_RC_SIZE_MISMATCH, "mbstowcs(%s)", src);

end:
	if (rc) {
		fsl_free(*dst);
		*dst = NULL;
		*dstlen = 0;
	}

	return rc;
}

/*
 * When the terminal is >= 110 columns wide, the commit summary line in the
 * timeline view will take the form:
 *
 *   DATE UUID USERNAME  COMMIT-COMMENT
 *
 * Assuming an 8-character username, this scheme provides 80 characters for the
 * comment, which should be sufficient considering it's suggested good practice
 * to limit commit comment summary lines to a maximum 50 characters, and most
 * plaintext-based conventions suggest not exceeding 72-80 characters.
 *
 * When < 110 columns, the (abbreviated 9-character) UUID will be elided.
 */
static int
write_commit_line(struct fnc_view *view, struct fnc_commit_artifact *commit,
    int max_usrlen)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fnc_colour		*c = NULL;
	wchar_t				*usr_wcstr = NULL, *wcomment = NULL;
	char				*comment0 = NULL, *comment = NULL;
	char				*date = NULL;
	char				*eol = NULL, *pad = NULL, *user = NULL;
	size_t				 i = 0;
	int				 col_pos, ncols_avail, usrlen;
	int				 commentlen, rc = 0;

	/* Trim time component from timestamp for the date field. */
	date = fsl_strdup(commit->timestamp);
	while (!fsl_isspace(date[i++])) {}
	date[i] = '\0';
	col_pos = MIN(view->ncols, ISO8601_DATE_ONLY + 1);
	if (s->colour)
		c = get_colour(&s->colours, FNC_DATE_STR);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddnstr(view->window, date, col_pos);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	if (col_pos > view->ncols)
		goto end;

	/* If enough columns, write abbreviated commit hash. */
	if (view->ncols >= 110) {
		if (s->colour)
			c = get_colour(&s->colours, FNC_COMMIT_ID);
		if (c)
			wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
		wprintw(view->window, "%.9s ", commit->uuid);
		if (c)
			wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
		col_pos += 10;
		if (col_pos > view->ncols)
			goto end;
	}

	/*
	 * Parse username from emailaddr if needed, and postfix username
	 * with as much whitespace as needed to fill two spaces beyond
	 * the longest username on the screen.
	 */
	user = fsl_strdup(commit->user);
	if (user == NULL)
		goto end;
	if (strpbrk(user, "<@>") != NULL)
		parse_emailaddr_username(&user);
	rc = formatln(&usr_wcstr, &usrlen, user, view->ncols - col_pos,
	    col_pos);
	if (rc)
		goto end;
	if (s->colour)
		c = get_colour(&s->colours, FNC_USER_STR);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, usr_wcstr);
	pad = fsl_mprintf("%*c",  max_usrlen - usrlen + 2, ' ');
	waddstr(view->window, pad);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	col_pos += (max_usrlen + 2);
	if (col_pos > view->ncols)
		goto end;

	/* Only show comment up to the first newline character. */
	comment0 = fsl_strdup(commit->comment);
	comment = comment0;
	if (comment == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	while (*comment == '\n')
		++comment;
	eol = strchr(comment, '\n');
	if (eol)
		*eol = '\0';
	ncols_avail = view->ncols - col_pos;
	rc = formatln(&wcomment, &commentlen, comment, ncols_avail, col_pos);
	if (rc)
		goto end;
	waddwstr(view->window, wcomment);
	col_pos += commentlen;
	while (col_pos < view->ncols) {
		waddch(view->window, ' ');
		++col_pos;
	}
end:
	fsl_free(date);
	fsl_free(user);
	fsl_free(usr_wcstr);
	fsl_free(pad);
	fsl_free(comment0);
	fsl_free(wcomment);
	return rc;
}

static int
view_input(struct fnc_view **new, int *done, struct fnc_view *view,
    struct view_tailhead *views)
{
	struct fnc_view	*v;
	int		 ch, rc = 0;

	*new = NULL;

	/* Clear search indicator string. */
	if (view->search_status == SEARCH_COMPLETE ||
	    view->search_status == SEARCH_NO_MATCH)
		view->search_status = SEARCH_CONTINUE;

	if (view->searching && view->search_status == SEARCH_WAITING) {
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		sched_yield();
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		rc = view->search_next(view);
		return rc;
	}

	nodelay(stdscr, FALSE);
	/* Allow thread to make progress while waiting for input. */
	if ((rc = pthread_mutex_unlock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");
	ch = wgetch(view->window);
	if ((rc = pthread_mutex_lock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	if (rec_sigwinch || rec_sigcont) {
		fnc_resizeterm();
		rec_sigwinch = 0;
		rec_sigcont = 0;
		TAILQ_FOREACH(v, views, entries) {
			if ((rc = view_resize(v)))
				return rc;
			if ((rc = v->input(new, v, KEY_RESIZE)))
				return rc;
			if (v->child) {
				if ((rc = view_resize(v->child)))
					return rc;
				rc = v->child->input(new, v->child, KEY_RESIZE);
				if (rc)
					return rc;
			}
		}
	}

	switch (ch) {
	case '\t':
		if (view->child) {
			view->active = false;
			view->child->active = true;
			view->focus_child = true;
		} else if (view->parent) {
			view->active = false;
			view->parent->active = true;
			view->parent->focus_child = false;
		}
		break;
	case KEY_F(1):
	case 'H':
	case '?':
		help(view);
		break;
	case 'q':
		rc = view->input(new, view, ch);
		view->egress = true;
		break;
	case 'f':
		if (view_is_parent(view)) {
			if (view->child == NULL)
				break;
			if (screen_is_split(view->child)) {
				view->active = false;
				view->child->active = true;
				rc = make_fullscreen(view->child);
			} else
				rc = make_splitscreen(view->child);
			if (rc)
				break;
			rc = view->child->input(new, view->child, KEY_RESIZE);
		} else {
			if (screen_is_split(view)) {
				view->parent->active = false;
				view->active = true;
				rc = make_fullscreen(view);
			} else
				rc = make_splitscreen(view);
			if (rc)
				break;
			rc = view->input(new, view, KEY_RESIZE);
		}
		break;
	case '/':
		if (view->search_init)
			view_search_start(view);
		else
			rc = view->input(new, view, ch);
		break;
	case 'N':
	case 'n':
		if (view->started_search && view->search_next) {
			view->searching = (ch == 'n' ?
			    SEARCH_FORWARD : SEARCH_REVERSE);
			view->search_status = SEARCH_WAITING;
			rc = view->search_next(view);
		} else
			rc = view->input(new, view, ch);
		break;
	case KEY_RESIZE:
		break;
	case ERR:
		break;
	case 'Q':
		*done = 1;
		break;
	default:
		rc = view->input(new, view, ch);
		break;
	}

	return rc;
}

static int
help(struct fnc_view *view)
{
	FILE			*help = NULL;
	char			*title = NULL;
	static const char	*keys[][2] = {
	    {""},
	    {""}, /* Global */
	    {"  H,?,F1           ", "  ❬H❭❬?❭❬F1❭      "},
	    {"  k,<Up>           ", "  ❬↑❭❬k❭          "},
	    {"  j,<Down>         ", "  ❬↓❭❬j❭          "},
	    {"  C-b,PgUp         ", "  ❬C-b❭❬PgUp❭     "},
	    {"  C-f,PgDn         ", "  ❬C-f❭❬PgDn❭     "},
	    {"  gg,Home          ", "  ❬gg❭❬Home❭      "},
	    {"  G,End            ", "  ❬G❭❬End❭        "},
	    {"  Tab              ", "  ❬TAB❭           "},
	    {"  c                ", "  ❬c❭             "},
	    {"  f                ", "  ❬f❭             "},
	    {"  /                ", "  ❬/❭             "},
	    {"  n                ", "  ❬n❭             "},
	    {"  N                ", "  ❬N❭             "},
	    {"  q                ", "  ❬q❭             "},
	    {"  Q                ", "  ❬Q❭             "},
	    {""},
	    {""}, /* Timeline */
	    {"  <,,              ", "  ❬<❭❬,❭          "},
	    {"  >,.              ", "  ❬>❭❬.❭          "},
	    {"  Enter,Space      ", "  ❬Enter❭❬Space❭  "},
	    {"  t                ", "  ❬t❭             "},
	    {""},
	    {""}, /* Diff */
	    {"  Space            ", "  ❬Space❭         "},
	    {"  i                ", "  ❬i❭             "},
	    {"  v                ", "  ❬v❭             "},
	    {"  w                ", "  ❬w❭             "},
	    {"  -,_              ", "  ❬-❭❬_❭          "},
	    {"  +,=              ", "  ❬+❭❬=❭          "},
	    {"  C-k,K,<,,        ", "  ❬C-k❭❬K❭❬<❭❬,❭  "},
	    {"  C-j,J,>,.        ", "  ❬C-j❭❬J❭❬>❭❬.❭  "},
	    {""},
	    {""}, /* Tree */
	    {"  l,Enter,<Right>  ", "  ❬→❭❬l❭❬Enter❭   "},
	    {"  h,<BS>,<Left>    ", "  ❬←❭❬h❭❬⌫❭       "},
	    {"  i                ", "  ❬i❭             "},
	    {"  t                ", "  ❬t❭             "},
	    {""},
	    {""}, /* Blame */
	    {"  Space            ", "  ❬Space❭         "},
	    {"  Enter            ", "  ❬Enter❭         "},
	    {"  b                ", "  ❬b❭             "},
	    {"  p                ", "  ❬p❭             "},
	    {"  B                ", "  ❬B❭             "},
	    {""},
	    {""}, /* Branch */
	    {"  Enter,Space      ", "  ❬Enter❭❬Space❭  "},
	    {"  d                ", "  ❬d❭             "},
	    {"  i                ", "  ❬i❭             "},
	    {"  t                ", "  ❬t❭             "},
	    {"  R,<C-l>          ", "  ❬R❭❬C-l❭        "},
	    {""},
	    {""},
	    {0}
	};
	static const char *desc[] = {
	    "",
	    "Global",
	    "Open in-app help",
	    "Move selection cursor or page up one line",
	    "Move selection cursor or page down one line",
	    "Scroll up one page",
	    "Scroll down one page",
	    "Jump to first line or start of the view",
	    "Jump to last line or end of the view",
	    "Switch focus between open views",
	    "Toggle coloured output",
            "Toggle fullscreen",
	    "Open prompt to enter search term (not available in this view)",
	    "Find next line or token matching the current search term",
	    "Find previous line or token matching the current search term",
            "Quit the active view",
	    "Quit the program",
	    "",
	    "Timeline",
	    "Move selection cursor up one commit",
	    "Move selection cursor down one commit",
	    "Open diff view of the selected commit",
	    "Display a tree reflecting the state of the selected commit",
	    "",
	    "Diff",
	    "Scroll down one page of diff output",
	    "Toggle inversion of diff output",
	    "Toggle verbosity of diff output",
	    "Toggle ignore whitespace-only changes in diff",
	    "Decrease the number of context lines",
	    "Increase the number of context lines",
	    "Display diff of next (newer) commit in the timeline",
	    "Display diff of previous (older) commit in the timeline",
	    "",
	    "Tree",
	    "Move into the selected directory",
	    "Return to the parent directory",
	    "Toggle display of file artifact SHA hashes",
	    "Display timeline of all commits modifying the selected entry",
	    "",
	    "Blame",
	    "Scroll down one page",
	    "Display the diff of the commit corresponding to the selected line",
	    "Blame the version of the file found in the selected line's commit",
	    "Blame the version of the file found in the selected line's parent "
	    "commit",
	    "Reload the previous blamed version of the file",
	    "",
	    "Branch",
	    "Display the timeline of the currently selected branch",
	    "Toggle display of the date when the branch last received changes",
	    "Toggle display of the SHA hash that identifies the branch",
	    "Open a tree view of the currently selected branch",
	    "Reload view with all repostory branches and no filters applied",
	    "",
	    "  See fnc(1) for complete list of options and key bindings."
	};
	int	cs, ln, width = 0, rc = 0;

	cs = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) ? 1 : 0;

	title = fsl_mprintf("%s %s Help\n", fcli_progname(), PRINT_VERSION);
	if (title == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");

	help = tmpfile();
	if (help == NULL)
		return RC(FSL_RC_IO, "%s", "tmpfile");

	/*
	 * Format help text, and compute longest line and total number of
	 * lines in text to be displayed to determine pad dimensions.
	 */
	width = fsl_strlen(title);
	for (ln = 0; keys[ln][0]; ++ln) {
		if (keys[ln][1]) {
			width = MAX((fsl_size_t)width,
			    fsl_strlen(keys[ln][cs]) + fsl_strlen(desc[ln]));
		}
		fsl_fprintf(help, "%s%s%c", keys[ln][cs], desc[ln],
		    keys[ln + 1] ? '\n' : 0);
	}
	rewind(help);

	rc = padpopup(view, width, ln, help, title);
	if (fclose(help) == EOF)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");

	fsl_free(title);
	return rc;
}

/*
 * Create popup pad in which to write the supplied txt string and optional
 * title. The pad is contained within a window that is offset four columns in
 * and two lines down from the parent window.
 */
static int
padpopup(struct fnc_view *view, int width, int height, FILE *txt,
    const char *title)
{
	WINDOW		*win, *content;
	char		*line = NULL;
	ssize_t		 linelen;
	size_t		 linesz;
	int		 ch, cury, end, wy, wx, x0, y0;

	x0 = 4;		/* Number of columns to border window. */
	y0 = 2;		/* Number of lines to border window. */
	cury = 0;
	wx = getmaxx(view->window) - ((x0 + 1) * 2); /* Width of window. */
	wy = getmaxy(view->window) - ((y0 + 1) * 2); /* Height of window */
	ch = ERR;

	if ((win = newwin(wy, wx, y0, x0)) == 0)
		return RC(FSL_RC_ERROR, "%s", "newwin");
	if ((content = newpad(height + 1, width + 1)) == 0) {
		delwin(win);
		return RC(FSL_RC_ERROR, "%s", "newpad");
	}

	doupdate();
	keypad(content, TRUE);

	/* Write text content to pad. */
	if (title)
		centerprint(content, 0, 0, width, title, 0);
	while ((linelen = getline(&line, &linesz, txt)) != -1)
		waddstr(content, line);
	fsl_free(line);

	end = (getcury(content) - (wy - 3));  /* No. lines past end of pad. */
	do {
		switch (ch) {
			case KEY_UP:
			case 'k':
				if (cury > 0)
					--cury;
				break;
			case KEY_DOWN:
			case 'j':
				if (cury < end)
					++cury;
				break;
			case KEY_PPAGE:
			case CTRL('b'):
				if (cury > 0) {
					cury -= wy / 2;
					if (cury < 0)
						cury = 0;
				}
				break;
			case KEY_NPAGE:
			case CTRL('f'):
			case ' ':
				if (cury < end) {
					cury += wy / 2;
					if (cury > end)
						cury = end;
				}
				break;
			case 'g':
				if (!fnc_home(view))
					break;
				/* FALL THROUGH */
			case KEY_HOME:
				cury = 0;
				break;
			case KEY_END:
			case 'G':
				cury = end;
				break;
			case ERR:
			default:
				break;
		}
		werase(win);
		box(win, 0, 0);
		wnoutrefresh(win);
		pnoutrefresh(content, cury, 0, y0 + 1, x0 + 1, wy, wx);
		doupdate();
	} while ((ch = wgetch(content)) != 'q' && ch != KEY_ESCAPE
	    && ch != ERR);

	/* Destroy window. */
	werase(win);
	wrefresh(win);
	delwin(win);
	delwin(content);

	/* Restore fnc window content. */
	touchwin(view->window);
	wnoutrefresh(view->window);
	doupdate();

	return 0;
}

static void
centerprint(WINDOW *win, int starty, int startx, int cols, const char *str,
    chtype colour)
{
	int	x, y;

	if (win == NULL)
		win = stdscr;

	getyx(win, y, x);
	x = startx ? startx : x;
	y = starty ? starty : y;
	if (!cols)
		cols = getmaxx(win);

	x = startx + (cols - fsl_strlen(str)) / 2;
	wattron(win, colour ? colour : A_UNDERLINE);
	mvwprintw(win, y, x, "%s", str);
	wattroff(win, colour ? colour : A_UNDERLINE);
	refresh();
}

static int
tl_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fnc_view			*diff_view = NULL, *tree_view = NULL;
	int				 rc = 0, start_col = 0;

	switch (ch) {
	case KEY_DOWN:
	case 'j':
	case '.':
	case '>':
		if (s->first_commit_onscreen == NULL)
			break;
		if (s->selected_idx < MIN(view->nlines - 2,
		    s->commits.ncommits - 1))
			++s->selected_idx;
		else if ((rc = timeline_scroll_down(view, 1)))
			break;
		select_commit(s);
		break;
	case KEY_NPAGE:
	case CTRL('f'): {
		struct commit_entry *first;
		if ((first = s->first_commit_onscreen) == NULL)
			break;
		if ((rc = timeline_scroll_down(view, view->nlines - 1)))
			break;
		if (first == s->first_commit_onscreen && s->selected_idx <
		    MIN(view->nlines - 2, s->commits.ncommits - 1))
			/* At bottom of timeline. */
			s->selected_idx = MIN(view->nlines - 2,
			    s->commits.ncommits - 1);
		select_commit(s);
		break;
	}
	case KEY_END:
	case 'G':
		view->search_status = SEARCH_FOR_END;
		view_search_start(view);
		break;
	case 'k':
	case KEY_UP:
	case '<':
	case ',':
		if (s->first_commit_onscreen == NULL)
			break;
		if (s->selected_idx > 0)
			--s->selected_idx;
		else
			timeline_scroll_up(s, 1);
		select_commit(s);
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->first_commit_onscreen == NULL)
			break;
		if (TAILQ_FIRST(&s->commits.head) == s->first_commit_onscreen)
			s->selected_idx = 0;
		else
			timeline_scroll_up(s, view->nlines - 1);
		select_commit(s);
		break;
	case 'g':
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	case KEY_HOME:
		if (s->first_commit_onscreen == NULL)
			break;
		s->selected_idx = 0;
		timeline_scroll_up(s, s->commits.ncommits);
		select_commit(s);
		break;
	case KEY_RESIZE:
		if (s->selected_idx > view->nlines - 2)
			s->selected_idx = view->nlines - 2;
		if (s->selected_idx > s->commits.ncommits - 1)
			s->selected_idx = s->commits.ncommits - 1;
		select_commit(s);
		if (s->commits.ncommits < view->nlines - 1 &&
		    !s->thread_cx.timeline_end) {
			s->thread_cx.ncommits_needed += (view->nlines - 1) -
			    s->commits.ncommits;
			rc = signal_tl_thread(view, 1);
		}
		break;
	case KEY_ENTER:
	case ' ':
	case '\r':
		if (s->selected_commit == NULL)
			break;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		if ((rc = init_diff_commit(&diff_view, start_col,
		    s->selected_commit->commit, view)))
			break;
		view->active = false;
		diff_view->active = true;
		if (view_is_parent(view)) {
			if (view->child != NULL) {
				rc = view_close(view->child);
				view->child = NULL;
			}
			if (rc)
				return rc;
			view->child = diff_view;
			diff_view->parent = view;
			view->focus_child = true;
		} else
			*new_view = diff_view;
		break;
	case 'c':
		s->colour = !s->colour;
		break;
	case 't':
		if (s->selected_commit == NULL)
			break;
		if (!fsl_rid_is_a_checkin(fcli_cx(),
		    s->selected_commit->commit->rid)) {
			wattr_on(view->window, A_BOLD, NULL);
			mvwaddstr(view->window,
			    view->start_ln + view->nlines - 1, 0,
			    "-- tree requires check-in artifact --");
			wclrtoeol(view->window);
			wattr_off(view->window, A_BOLD, NULL);
			fcli_err_reset();
			rc = 0;
			update_panels();
			doupdate();
			sleep(1);
			break;
		}
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		rc = browse_commit_tree(&tree_view, start_col,
		    s->selected_commit, s->path);
		if (rc)
			break;
		s->thread_cx.tree_open = true;
		view->active = false;
		tree_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				return rc;
			view_set_child(view, tree_view);
			view->focus_child = true;
		} else
			*new_view = tree_view;
		break;
	case 'q':
		s->quit = 1;
		break;
	default:
		break;
	}

	return rc;
}

static int
timeline_scroll_down(struct fnc_view *view, int maxscroll)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct commit_entry		*pentry;
	int				 rc = 0, nscrolled = 0, ncommits_needed;

	if (s->last_commit_onscreen == NULL)
		return 0;

	ncommits_needed = s->last_commit_onscreen->idx + 1 + maxscroll;
	if (s->commits.ncommits < ncommits_needed &&
	    !s->thread_cx.timeline_end) {
		/* Signal timeline thread for n commits needed. */
		s->thread_cx.ncommits_needed += maxscroll;
		rc = signal_tl_thread(view, 1);
		if (rc)
			return rc;
	}

	do {
		pentry = TAILQ_NEXT(s->last_commit_onscreen, entries);
		if (pentry == NULL)
			break;

		s->last_commit_onscreen = pentry;

		pentry = TAILQ_NEXT(s->first_commit_onscreen, entries);
		if (pentry == NULL)
			break;
		s->first_commit_onscreen = pentry;
	} while (++nscrolled < maxscroll);

	return rc;
}

static void
timeline_scroll_up(struct fnc_tl_view_state *s, int maxscroll)
{
	struct commit_entry	*entry;
	int			 nscrolled = 0;

	entry = TAILQ_FIRST(&s->commits.head);
	if (s->first_commit_onscreen == entry)
		return;

	entry = s->first_commit_onscreen;
	while (entry && nscrolled < maxscroll) {
		entry = TAILQ_PREV(entry, commit_tailhead, entries);
		if (entry) {
			s->first_commit_onscreen = entry;
			++nscrolled;
		}
	}
}

static void
select_commit(struct fnc_tl_view_state *s)
{
	struct commit_entry	*entry;
	int			 ncommits = 0;

	entry = s->first_commit_onscreen;
	while (entry) {
		if (ncommits == s->selected_idx) {
			s->selected_commit = entry;
			break;
		}
		entry = TAILQ_NEXT(entry, entries);
		++ncommits;
	}
}

static int
make_splitscreen(struct fnc_view *view)
{
	int	 rc = 0;

	view->start_ln = 0;
	view->start_col = view_split_start_col(0);
	view->nlines = LINES;
	view->ncols = COLS - view->start_col;
	view->lines = LINES;
	view->cols = COLS;
	if ((rc = view_resize(view)))
		return rc;

	if (mvwin(view->window, view->start_ln, view->start_col) == ERR)
		return RC(FSL_RC_ERROR, "%s", "mvwin");

	return rc;
}

static int
make_fullscreen(struct fnc_view *view)
{
	int	 rc = 0;

	view->start_col = 0;
	view->start_ln = 0;
	view->nlines = LINES;
	view->ncols = COLS;
	view->lines = LINES;
	view->cols = COLS;
	if ((rc = view_resize(view)))
		return rc;

	if (mvwin(view->window, view->start_ln, view->start_col) == ERR)
		return RC(FSL_RC_ERROR, "%s", "mvwin");

	return rc;
}

/*
 * Only open a new view in a splitscreen if the console is >= 120 columns wide.
 * Otherwise, open in the current view. If splitting the screen, make the new
 * panel the largest of 80 columns or half the current column width.
 */
static int
view_split_start_col(int start_col)
{
	if (start_col > 0 || COLS < 120)
		return 0;
	return (COLS - MAX(COLS / 2, 80));
}

static int
view_search_start(struct fnc_view *view)
{
	char	pattern[BUFSIZ];
	int	retval;
	int	rc = 0;

	if (view->started_search) {
		regfree(&view->regex);
		view->searching = SEARCH_DONE;
		memset(&view->regmatch, 0, sizeof(view->regmatch));
	}
	view->started_search = false;

	if (view->nlines < 1)
		return rc;

	if (view->search_status == SEARCH_FOR_END) {
		view->search_init(view);
		view->started_search = true;
		view->searching = SEARCH_FORWARD;
		view->search_status = SEARCH_WAITING;
		view->state.timeline.thread_cx.endjmp = true;
		rc = view->search_next(view);

		return rc;
	}

	mvwaddstr(view->window, view->start_ln + view->nlines - 1, 0, "/");
	wclrtoeol(view->window);

	nocbreak();
	echo();
	retval = wgetnstr(view->window, pattern, sizeof(pattern));
	cbreak();
	noecho();
	if (retval == ERR)
		return rc;

	if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
		if ((rc = view->search_init(view))) {
			regfree(&view->regex);
			return rc;
		}
		view->started_search = true;
		view->searching = SEARCH_FORWARD;
		view->search_status = SEARCH_WAITING;
		rc = view->search_next(view);
	}

	return rc;
}

static int
tl_search_init(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;

	s->matched_commit = NULL;
	s->search_commit = NULL;
	return 0;
}

static int
tl_search_next(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct commit_entry		*entry;
	int				 rc = 0;

	if (!s->thread_cx.ncommits_needed && view->started_search)
		halfdelay(1);

	/* Show status update in timeline view. */
	show_timeline_view(view);
	update_panels();
	doupdate();

	if (s->search_commit) {
		int	ch;
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		ch = wgetch(view->window);
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		if (ch == KEY_BACKSPACE) {
			view->search_status = SEARCH_CONTINUE;
			return rc;
		}
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_NEXT(s->search_commit, entries);
		else
			entry = TAILQ_PREV(s->search_commit, commit_tailhead,
			    entries);
	} else if (s->matched_commit) {
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_NEXT(s->matched_commit, entries);
		else
			entry = TAILQ_PREV(s->matched_commit, commit_tailhead,
			    entries);
	} else {
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_FIRST(&s->commits.head);
		else
			entry = TAILQ_LAST(&s->commits.head, commit_tailhead);
	}

	while (1) {
		if (entry == NULL) {
			if (s->thread_cx.timeline_end && s->thread_cx.endjmp) {
				s->matched_commit = TAILQ_LAST(&s->commits.head,
				    commit_tailhead);
				view->search_status = SEARCH_COMPLETE;
				s->thread_cx.endjmp = false;
				break;
			}
			if (s->thread_cx.timeline_end || view->searching ==
			    SEARCH_REVERSE) {
				view->search_status = (s->matched_commit ==
				    NULL ?  SEARCH_NO_MATCH : SEARCH_COMPLETE);
				s->search_commit = NULL;
				cbreak();
				return rc;
			}
			/*
			 * Wake the timeline thread to produce more commits.
			 * Search will resume at s->search_commit upon return.
			 */
			++s->thread_cx.ncommits_needed;
			return signal_tl_thread(view, 0);
		}

		if (!s->thread_cx.endjmp && find_commit_match(entry->commit,
		    &view->regex)) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_commit = entry;
			break;
		}

		s->search_commit = entry;
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_NEXT(entry, entries);
		else
			entry = TAILQ_PREV(entry, commit_tailhead, entries);
	}

	if (s->matched_commit) {
		int cur = s->selected_commit->idx;
		while (cur < s->matched_commit->idx) {
			if ((rc = tl_input_handler(NULL, view, KEY_DOWN)))
				return rc;
			++cur;
		}
		while (cur > s->matched_commit->idx) {
			if ((rc = tl_input_handler(NULL, view, KEY_UP)))
				return rc;
			--cur;
		}
	}

	s->search_commit = NULL;
	cbreak();

	return rc;
}

static bool
find_commit_match(struct fnc_commit_artifact *commit,
regex_t *regex)
{
	regmatch_t	regmatch;

	if (regexec(regex, commit->user, 1, &regmatch, 0) == 0 ||
	    regexec(regex, (char *)commit->uuid, 1, &regmatch, 0) == 0 ||
	    regexec(regex, commit->comment, 1, &regmatch, 0) == 0 ||
	    (commit->branch && regexec(regex, commit->branch, 1, &regmatch, 0)
	     == 0))
		return true;

	return false;
}

static int
view_close(struct fnc_view *view)
{
        int	rc = 0;

	if (view->child) {
		view_close(view->child);
		view->child = NULL;
	}
	if (view->close)
		rc = view->close(view);
	if (view->panel)
		del_panel(view->panel);
	if (view->window)
		delwin(view->window);
	free(view);

	return rc;
}

static int
close_timeline_view(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fsl_list_state		 st = { FNC_COLOUR_OBJ };
	int				 rc = 0;

	rc = join_tl_thread(s);
	fsl_stmt_finalize(s->thread_cx.q);
	fnc_free_commits(&s->commits);
	fsl_list_clear(&s->colours, fsl_list_object_free, &st);
	regfree(&view->regex);
	fsl_free(s->path);
	s->path = NULL;

	return rc;
}

/* static void */
/* sspinner(void) */
/* { */
/* 	int idx; */

/* 	while (1) { */
/* 		for (idx = 0; idx < 4; ++idx) { */
/* 			printf("\b%c", "|/-\\"[idx]); */
/* 			fflush(stdout); */
/* 			ssleep(SPIN_INTERVAL); */
/* 		} */
/* 	} */
/* } */

static int
join_tl_thread(struct fnc_tl_view_state *s)
{
	void	*err;
	int	 rc = 0;

	if (s->thread_id) {
		s->quit = 1;

		if ((rc = pthread_cond_signal(&s->thread_cx.commit_consumer)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_cond_signal");
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		if ((rc = pthread_join(s->thread_id, &err)) ||
		    err == PTHREAD_CANCELED)
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_join");
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");

		s->thread_id = 0;
	}

	if ((rc = pthread_cond_destroy(&s->thread_cx.commit_consumer)))
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_destroy");

	if ((rc = pthread_cond_destroy(&s->thread_cx.commit_producer)))
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_destroy");

	return rc;
}

static void
fnc_free_commits(struct commit_queue *commits)
{
	while (!TAILQ_EMPTY(&commits->head)) {
		struct commit_entry	*entry;

		entry = TAILQ_FIRST(&commits->head);
		TAILQ_REMOVE(&commits->head, entry, entries);
		fnc_commit_artifact_close(entry->commit);
		free(entry);
		--commits->ncommits;
	}
}

static void
fnc_commit_artifact_close(struct fnc_commit_artifact *commit)
{
	struct fsl_list_state	st = { FNC_ARTIFACT_OBJ };

	if (commit->branch)
		fsl_free(commit->branch);
	if (commit->comment)
		fsl_free(commit->comment);
	if (commit->timestamp)
		fsl_free(commit->timestamp);
	if (commit->type)
		fsl_free(commit->type);
	if (commit->user)
		fsl_free(commit->user);
	fsl_free(commit->uuid);
	fsl_free(commit->puuid);
	fsl_list_clear(&commit->changeset, fsl_list_object_free, &st);
	fsl_list_reserve(&commit->changeset, 0);
	fsl_free(commit);
}

static int
fsl_list_object_free(void *elem, void *state)
{
	struct fsl_list_state *st = state;

	switch (st->obj) {
	case FNC_ARTIFACT_OBJ: {
		struct fsl_file_artifact *ffa = elem;
		fsl_free(ffa->fc->name);
		fsl_free(ffa->fc->uuid);
		fsl_free(ffa->fc->priorName);
		fsl_free(ffa->fc);
		fsl_free(ffa);
		break;
	}
	case FNC_COLOUR_OBJ: {
		struct fnc_colour *c = elem;
		regfree(&c->regex);
		fsl_free(c);
		break;
	}
	default:
		return RC(FSL_RC_MISSING_INFO,
		    "fsl_list_state.obj missing or invalid: %d", st->obj);
	}

	return 0;
}

static int
init_diff_commit(struct fnc_view **new_view, int start_col,
    struct fnc_commit_artifact *commit, struct fnc_view *timeline_view)
{
	struct fnc_view			*diff_view;
	int				 rc = 0;

	diff_view = view_open(0, 0, 0, start_col, FNC_VIEW_DIFF);
	if (diff_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_diff_view(diff_view, commit, DIFF_DEF_CTXT, fnc_init.ws,
	    fnc_init.invert, !fnc_init.quiet, timeline_view, true, NULL);
	if (!rc)
		*new_view = diff_view;

	return rc;
}

static int
open_diff_view(struct fnc_view *view, struct fnc_commit_artifact *commit,
    int context, bool ignore_ws, bool invert, bool verbosity,
    struct fnc_view *timeline_view, bool showmeta,
    struct fnc_pathlist_head *paths)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	int				 rc = 0;

	s->paths = paths;
	s->selected_commit = commit;
	s->first_line_onscreen = 1;
	s->last_line_onscreen = view->nlines;
	s->current_line = 1;
	s->f = NULL;
	s->context = context;
	s->sbs = 0;
	verbosity ? s->diff_flags |= FSL_DIFF_VERBOSE : 0;
	ignore_ws ? s->diff_flags |= FSL_DIFF_IGNORE_ALLWS : 0;
	invert ? s->diff_flags |= FSL_DIFF_INVERT : 0;
	s->timeline_view = timeline_view;
	s->colours = fsl_list_empty;
	s->colour = !fnc_init.nocolour && has_colors();
	s->showmeta = showmeta;

	if (s->colour)
		set_colours(&s->colours, FNC_VIEW_DIFF);
	if (timeline_view && screen_is_split(view))
		show_timeline_view(timeline_view); /* draw vborder */
	show_diff_status(view);

	s->line_offsets = NULL;
	s->nlines = 0;
	s->ncols = view->ncols;
	rc = create_diff(s);
	if (rc) {
		if (s->colour) {
			struct fsl_list_state st = { FNC_COLOUR_OBJ };
			fsl_list_clear(&s->colours, fsl_list_object_free, &st);
		}
		return rc;
	}

	view->show = show_diff;
	view->input = diff_input_handler;
	view->close = close_diff_view;
	view->search_init = diff_search_init;
	view->search_next = diff_search_next;

	return rc;
}

static void
show_diff_status(struct fnc_view *view)
{
	mvwaddstr(view->window, 0, 0, "generating diff...");
#ifdef __linux__
	wnoutrefresh(view->window);
#else
	update_panels();
#endif
	doupdate();
}

static int
create_diff(struct fnc_diff_view_state *s)
{
	FILE	*fout = NULL;
	char	*line, *st0 = NULL, *st = NULL;
	off_t	 lnoff = 0;
	int	 n, rc = 0;

	free(s->line_offsets);
	s->line_offsets = fsl_malloc(sizeof(off_t));
	if (s->line_offsets == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	s->nlines = 0;

	fout = tmpfile();
	if (fout == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "tmpfile");
		goto end;
	}
	if (s->f && fclose(s->f) == EOF) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");
		goto end;
	}
	s->f = fout;

	/*
	 * We'll diff artifacts of type "ci" (i.e., "checkin") separately, as
	 * it's a different process to diff the others (wiki, technote, etc.).
	 */
	if (s->selected_commit->diff_type == FNC_DIFF_COMMIT)
		rc = create_changeset(s->selected_commit);
	else if (s->selected_commit->diff_type == FNC_DIFF_BLOB)
		rc = diff_file_artifact(&s->buf, s->selected_commit->prid, NULL,
		    s->selected_commit->rid, NULL, FSL_CKOUT_CHANGE_MOD,
		    s->diff_flags, s->context, s->sbs,
		    s->selected_commit->diff_type);
	else if (s->selected_commit->diff_type == FNC_DIFF_WIKI)
		rc = diff_non_checkin(&s->buf, s->selected_commit,
		    s->diff_flags, s->context, s->sbs);
	if (rc)
		goto end;

	/*
	 * Delay assigning diff headline labels (i.e., diff id1 id2) till now
	 * because wiki parent commits are obtained in diff_non_checkin().
	 */
	if (s->selected_commit->puuid) {
		s->id1 = fsl_strdup(s->selected_commit->puuid);
		if (s->id1 == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else
		s->id1 = NULL;	/* Initial commit, tag, technote, etc. */
	if (s->selected_commit->uuid) {
		s->id2 = fsl_strdup(s->selected_commit->uuid);
		if (s->id2 == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else
		s->id2 = NULL;	/* Local work tree. */

	rc = add_line_offset(&s->line_offsets, &s->nlines, 0);
	if (rc)
		goto end;

	if (s->showmeta)
		write_commit_meta(s);

	/*
	 * Diff local changes on disk in the current checkout differently to
	 * checked-in versions: the former compares on disk file content with
	 * file artifacts; the latter compares file artifact blobs only.
	 */
	if (s->selected_commit->diff_type == FNC_DIFF_COMMIT)
		diff_commit(&s->buf, s->selected_commit, s->diff_flags,
		    s->context, s->sbs, s->paths);
	else if (s->selected_commit->diff_type == FNC_DIFF_CKOUT)
		diff_checkout(&s->buf, s->selected_commit->prid, s->diff_flags,
		    s->context, s->sbs, s->paths);

	/*
	 * Parse the diff buffer line-by-line to record byte offsets of each
	 * line for scrolling and searching in diff view.
	 */
	st0 = fsl_strdup(fsl_buffer_str(&s->buf));
	st = st0;
	lnoff = (s->line_offsets)[s->nlines - 1];
	while ((line = fnc_strsep(&st, "\n")) != NULL) {
		n = fprintf(s->f, "%s\n", line);
		lnoff += n;
		rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff);
		if (rc)
			goto end;
	}

	fputc('\n', s->f);
	++lnoff;
	rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff);
	if (rc)
		goto end;

end:
	free(st0);
	fsl_buffer_clear(&s->buf);
	if (s->f && fflush(s->f) != 0 && rc == 0)
		rc = RC(FSL_RC_IO, "%s", "fflush");
	return rc;
}

static int
create_changeset(struct fnc_commit_artifact *commit)
{
	fsl_cx		*f = fcli_cx();
	fsl_stmt	*st = NULL;
	fsl_list	 changeset = fsl_list_empty;
	int		 rc = 0;

	st = fsl_stmt_malloc();
	rc = fsl_cx_prepare(f, st,
	    "SELECT name, mperm, "
	    "(SELECT uuid FROM blob WHERE rid=mlink.pid), "
	    "(SELECT uuid FROM blob WHERE rid=mlink.fid), "
	    "(SELECT name FROM filename WHERE filename.fnid=mlink.pfnid) "
	    "FROM mlink JOIN filename ON filename.fnid=mlink.fnid "
	    "WHERE mlink.mid=%d AND NOT mlink.isaux "
	    "AND (mlink.fid > 0 "
	    "OR mlink.fnid NOT IN (SELECT pfnid FROM mlink WHERE mid=%d)) "
	    "ORDER BY name", commit->rid, commit->rid);
	if (rc)
		return RC(FSL_RC_DB, "%s", "fsl_cx_prepare");

	while ((rc = fsl_stmt_step(st)) == FSL_RC_STEP_ROW) {
		struct fsl_file_artifact *fdiff = NULL;
		const char *path, *oldpath, *olduuid, *uuid;
		/* TODO: Parse file mode to display in commit changeset. */
		/* int perm; */

		path = fsl_stmt_g_text(st, 0, NULL);	/* Current filename. */
		//perm = fsl_stmt_g_int32(st, 1);	/* File permissions. */
		olduuid = fsl_stmt_g_text(st, 2, NULL);	/* UUID before change */
		uuid = fsl_stmt_g_text(st, 3, NULL);	/* UUID after change. */
		oldpath = fsl_stmt_g_text(st, 4, NULL);	/* Old name, if chngd */

		fdiff = fsl_malloc(sizeof(struct fsl_file_artifact));
		fdiff->fc = fsl_malloc(sizeof(fsl_card_F));
		*fdiff->fc = fsl_card_F_empty;
		fdiff->fc->name = fsl_strdup(path);
		if (!uuid) {
			fdiff->fc->uuid = fsl_strdup(olduuid);
			fdiff->change = FSL_CKOUT_CHANGE_REMOVED;
		} else if (!olduuid) {
			fdiff->fc->uuid = fsl_strdup(uuid);
			fdiff->change = FSL_CKOUT_CHANGE_ADDED;
		} else if (oldpath) {
			fdiff->fc->uuid = fsl_strdup(uuid);
			fdiff->fc->priorName = fsl_strdup(oldpath);
			fdiff->change = FSL_CKOUT_CHANGE_RENAMED;
		} else {
			fdiff->fc->uuid = fsl_strdup(uuid);
			fdiff->change = FSL_CKOUT_CHANGE_MOD;
		}
		fsl_list_append(&changeset, fdiff);
	}

	commit->changeset = changeset;
	fsl_stmt_finalize(st);

	if (rc == FSL_RC_STEP_DONE)
		rc = 0;

	return rc;
}

static int
write_commit_meta(struct fnc_diff_view_state *s)
{
	char		*line = NULL, *st0 = NULL, *st = NULL;
	fsl_size_t	 linelen, idx = 0;
	off_t		 lnoff = 0;
	int		 n, rc = 0;

	if ((n = fprintf(s->f,"%s %s\n", s->selected_commit->type,
	    s->selected_commit->uuid)) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	if ((n = fprintf(s->f,"user: %s\n", s->selected_commit->user)) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	if ((n = fprintf(s->f,"tags: %s\n", s->selected_commit->branch ?
	    s->selected_commit->branch : "/dev/null")) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	if ((n = fprintf(s->f,"date: %s\n",
	    s->selected_commit->timestamp)) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	fputc('\n', s->f);
	++lnoff;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	st0 = fsl_strdup(s->selected_commit->comment);
	st = st0;
	if (st == NULL) {
		RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}
	while ((line = fnc_strsep(&st, "\n")) != NULL) {
		linelen = fsl_strlen(line);
		if (linelen >= s->ncols) {
			rc = wrapline(line, s->ncols, s, &lnoff);
			if (rc)
				goto end;
		}
		else {
			if ((n = fprintf(s->f, "%s\n", line)) < 0)
				goto end;
			lnoff += n;
			if ((rc = add_line_offset(&s->line_offsets, &s->nlines,
			    lnoff)))
				goto end;

		}
	}

	fputc('\n', s->f);
	++lnoff;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	for (idx = 0; idx < s->selected_commit->changeset.used; ++idx) {
		char				*changeline;
		struct fsl_file_artifact	*file_change;

		file_change = s->selected_commit->changeset.list[idx];

		switch (file_change->change) {
		case FSL_CKOUT_CHANGE_MOD:
			changeline = "[~] ";
			break;
		case FSL_CKOUT_CHANGE_ADDED:
			changeline = "[+] ";
			break;
		case FSL_CKOUT_CHANGE_RENAMED:
			changeline = fsl_mprintf("[>] %s -> ",
			   file_change->fc->priorName);
			break;
		case FSL_CKOUT_CHANGE_REMOVED:
			changeline = "[-] ";
			break;
		default:
			changeline = "[!] ";
			break;
		}
		if ((n = fprintf(s->f, "%s%s\n", changeline,
		    file_change->fc->name)) < 0)
			goto end;
		lnoff += n;
		if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
			goto end;
	}

end:
	free(st0);
	free(line);
	if (rc) {
		free(*&s->line_offsets);
		s->line_offsets = NULL;
		s->nlines = 0;
	}
	return rc;
}

/*
 * Wrap long lines at the terminal's available column width. The caller
 * must ensure the ncols_avail parameter has taken into account whether the
 * screen is currently split, and not mistakenly pass in the curses COLS macro
 * without deducting the parent panel's width. This function doesn't break
 * words, and will wrap at the end of the last word that can wholly fit within
 * the ncols_avail limit.
 */
static int
wrapline(char *line, fsl_size_t ncols_avail, struct fnc_diff_view_state *s,
    off_t *lnoff)
{
	char		*word;
	fsl_size_t	 wordlen, cursor = 0;
	int		 n = 0, rc = 0;

	while ((word = fnc_strsep(&line, " ")) != NULL) {
		wordlen = fsl_strlen(word);
		if ((cursor + wordlen) >= ncols_avail) {
			fputc('\n', s->f);
			++(*lnoff);
			rc = add_line_offset(&s->line_offsets, &s->nlines,
			    *lnoff);
			if (rc)
				return rc;
			cursor = 0;
		}
		if ((n  = fprintf(s->f, "%s ", word)) < 0)
			return rc;
		*lnoff += n;
		cursor += n;
	}
	fputc('\n', s->f);
	++(*lnoff);
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, *lnoff)))
		return rc;

	return 0;
}

static int
add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
{
	off_t	*p;

	p = fsl_realloc(*line_offsets, (*nlines + 1) * sizeof(off_t));
	if (p == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_realloc");
	*line_offsets = p;
	(*line_offsets)[*nlines] = off;
	(*nlines)++;

	return 0;
}

/*
 * Fill the buffer with the differences between commit->uuid and commit->puuid.
 * commit->rid (to load into deck d2) is the *this* version, and commit->puuid
 * (to be loaded into deck d1) is the version we diff against. Step through the
 * deck of F(ile) cards from both versions to determine: (1) if we have new
 * files added (i.e., no F card counterpart in d1); (2) files deleted (i.e., no
 * F card counterpart in d2); (3) or otherwise the same file (i.e., F card
 * exists in both d1 and d2). In cases (1) and (2), we call diff_file_artifact()
 * to dump the complete content of the added/deleted file if FSL_DIFF_VERBOSE is
 * set, otherwise only diff metatadata will be output. In case (3), if the
 * hash (UUID) of each F card is the same, there are no changes; if different,
 * both artifacts will be passed to diff_file_artifact() to be diffed.
 */
static int
diff_commit(fsl_buffer *buf, struct fnc_commit_artifact *commit, int diff_flags,
    int context, int sbs, struct fnc_pathlist_head *paths)
{
	fsl_cx			*f = fcli_cx();
	const fsl_card_F	*fc1 = NULL;
	const fsl_card_F	*fc2 = NULL;
	fsl_deck		 d1 = fsl_deck_empty;
	fsl_deck		 d2 = fsl_deck_empty;
	fsl_id_t		 id1;
	int			 different = 0, rc = 0;

	rc = fsl_deck_load_rid(f, &d2, commit->rid, FSL_SATYPE_CHECKIN);
	if (rc)
		goto end;
	rc = fsl_deck_F_rewind(&d2);
	if (rc)
		goto end;

	/*
	 * For the one-and-only special case of repositories, such as the
	 * canonical fnc, that do not have an "initial empty check-in", we
	 * proceed with no parent version to diff against.
	 */
	if (commit->puuid) {
		rc = fsl_sym_to_rid(f, commit->puuid, FSL_SATYPE_CHECKIN, &id1);
		if (rc)
			goto end;
		rc = fsl_deck_load_rid(f, &d1, id1, FSL_SATYPE_CHECKIN);
		if (rc)
			goto end;
		rc = fsl_deck_F_rewind(&d1);
		if (rc)
			goto end;
		fsl_deck_F_next(&d1, &fc1);
	}

	fsl_deck_F_next(&d2, &fc2);
	while (fc1 || fc2) {
		const fsl_card_F	*a = NULL, *b = NULL;
		fsl_ckout_change_e	 change = FSL_CKOUT_CHANGE_NONE;
		bool			 diff = true;

		if (paths != NULL && !TAILQ_EMPTY(paths)) {
			struct fnc_pathlist_entry *pe;
			diff = false;
			TAILQ_FOREACH(pe, paths, entry)
				if (!fsl_strcmp(pe->path, fc1->name) ||
				    !fsl_strcmp(pe->path, fc2->name) ||
				    !fsl_strncmp(pe->path, fc1->name,
				    pe->pathlen) || !fsl_strncmp(pe->path,
				    fc2->name, pe->pathlen)) {
					diff = true;
					break;
				}
		}

		if (!fc1)	/* File added. */
			different = 1;
		else if (!fc2)	/* File deleted. */
			different = -1;
		else		/* Same filename in both versions. */
			different = fsl_strcmp(fc1->name, fc2->name);

		if (different) {
			if (different > 0) {
				b = fc2;
				change = FSL_CKOUT_CHANGE_ADDED;
				fsl_deck_F_next(&d2, &fc2);
			} else if (different < 0) {
				a = fc1;
				change = FSL_CKOUT_CHANGE_REMOVED;
				fsl_deck_F_next(&d1, &fc1);
			}
			if (diff)
				rc = diff_file_artifact(buf, id1, a,
				    commit->rid, b, change, diff_flags,
				    context, sbs, commit->diff_type);
		} else if (!fsl_uuidcmp(fc1->uuid, fc2->uuid)) { /* No change */
			fsl_deck_F_next(&d1, &fc1);
			fsl_deck_F_next(&d2, &fc2);
		} else {
			change = FSL_CKOUT_CHANGE_MOD;
			if (diff)
				rc = diff_file_artifact(buf, id1, fc1,
				    commit->rid, fc2, change, diff_flags,
				    context, sbs, commit->diff_type);
			fsl_deck_F_next(&d1, &fc1);
			fsl_deck_F_next(&d2, &fc2);
		}
		if (rc == FSL_RC_RANGE) {
			fsl_buffer_append(buf,
			    "\nDiff has too many changes\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc == FSL_RC_DIFF_BINARY) {
			fsl_buffer_append(buf,
			    "\nBinary files cannot be diffed\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc)
			goto end;
	}
end:
	fsl_deck_finalize(&d1);
	fsl_deck_finalize(&d2);
	return rc;
}

/*
 * Diff local changes on disk in the current checkout against either a previous
 * commit or, if no version has been supplied, the current checkout.
 *   buf  output buffer in which diff content is appended
 *   vid  repository database record id of the version to diff against
 * diff_flags, context, and sbs are the same parameters as diff_file_artifact()
 * nb. This routine is only called with 'fnc diff [hash]'; that is, one or
 * zero args—not two—supplied to fnc's diff command line interface.
 */
static int
diff_checkout(fsl_buffer *buf, fsl_id_t vid, int diff_flags, int context,
    int sbs, struct fnc_pathlist_head *paths)
{
	fsl_cx		*f = fcli_cx();
	fsl_stmt	*st = NULL;
	fsl_buffer	 sql, abspath, bminus;
	fsl_uuid_str	 xminus = NULL;
	fsl_id_t	 cid;
	int		 rc = 0;
	bool		 allow_symlinks;

	abspath = bminus = sql = fsl_buffer_empty;
	fsl_ckout_version_info(f, &cid, NULL);
	/* cid = fsl_config_get_id(f, FSL_CONFDB_CKOUT, 0, "checkout"); */
	/* XXX Already done in cmd_diff(): Load vfile table with local state. */
	/* rc = fsl_vfile_changes_scan(f, cid, */
	/*     FSL_VFILE_CKSIG_ENOTFILE & FSL_VFILE_CKSIG_KEEP_OTHERS); */
	/* if (rc) */
	/*	return RC(rc, "%s", "fsl_vfile_changes_scan"); */

	/*
	 * If a previous version is supplied, load its vfile state to query
	 * changes. Otherwise query the current checkout state for changes.
	 */
	if (vid != cid) {
		/* Keep vfile ckout state; but unload vid when finished. */
		rc = fsl_vfile_load(f, vid, false, NULL);
		if (rc)
			goto unload;
		fsl_buffer_appendf(&sql, "SELECT v2.pathname, v2.deleted, "
		    "v2.chnged, v2.rid == 0, v1.rid, v1.islink"
		    " FROM vfile v1, vfile v2"
		    " WHERE v1.pathname=v2.pathname AND v1.vid=%d AND v2.vid=%d"
		    " AND (v2.deleted OR v2.chnged OR v1.mrid != v2.rid)"
		    " UNION "
		    "SELECT pathname, 1, 0, 0, 0, islink"
		    " FROM vfile v1"
		    " WHERE v1.vid = %d"
		    " AND NOT EXISTS(SELECT 1 FROM vfile v2"
		    " WHERE v2.vid = %d AND v2.pathname = v1.pathname)"
		    " UNION "
		    "SELECT pathname, 0, 0, 1, 0, islink"
		    " FROM vfile v2"
		    " WHERE v2.vid = %d"
		    " AND NOT EXISTS(SELECT 1 FROM vfile v1"
		    " WHERE v1.vid = %d AND v1.pathname = v2.pathname)"
		    " ORDER BY 1", vid, cid, vid, cid, cid, vid);
	} else {
		fsl_buffer_appendf(&sql, "SELECT pathname, deleted, chnged, "
		    "rid == 0, rid, islink"
		    " FROM vfile"
		    " WHERE vid = %d"
		    " AND (deleted OR chnged OR rid == 0)"
		    " ORDER BY pathname", cid);
	}
	st = fsl_stmt_malloc();
	rc = fsl_cx_prepare(f, st, "%b", &sql);
	if (rc) {
		rc = RC(rc, "%s", "fsl_cx_prepare");
		goto yield;
	}

	while ((rc = fsl_stmt_step(st)) == FSL_RC_STEP_ROW) {
		const char	*path;
		int		 deleted, changed, added, fid, symlink;
		enum		 fsl_ckout_change_e change;
		bool		 diff = true;

		path = fsl_stmt_g_text(st, 0, NULL);
		deleted = fsl_stmt_g_int32(st, 1);
		changed = fsl_stmt_g_int32(st, 2);
		added = fsl_stmt_g_int32(st, 3);
		fid = fsl_stmt_g_int32(st, 4);
		symlink = fsl_stmt_g_int32(st, 5);
		rc = fsl_file_canonical_name2(f->ckout.dir, path, &abspath,
		    false);
		if (rc)
			goto yield;

		if (deleted)
			change = FSL_CKOUT_CHANGE_REMOVED;
		else if (fsl_file_access(fsl_buffer_cstr(&abspath), F_OK))
			change = FSL_CKOUT_CHANGE_MISSING;
		else if (added) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_ADDED;
		} else if (changed == 3) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_MERGE_ADD;
		} else if (changed == 5) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_INTEGRATE_ADD;
		} else
			change = FSL_CKOUT_CHANGE_MOD;

		/*
		 * For changed files of which this checkout is already aware,
		 * grab their hash to make comparisons. For removed files, if
		 * diffing against a version other than the current checkout,
		 * load the version's manifest to parse for known versions of
		 * said files. If we don't, we risk diffing stale or bogus
		 * content. Known cases include MISSING, DELETED, and RENAMED
		 * files, which fossil(1) misses in some instances.
		 */
		if (fid > 0)
			xminus = fsl_rid_to_uuid(f, fid);
		else if (vid != cid && !added) {
			fsl_deck		 d = fsl_deck_empty;
			const fsl_card_F	*cf = NULL;

			rc = fsl_deck_load_rid(f, &d, vid, FSL_SATYPE_CHECKIN);
			if (!rc)
				rc = fsl_deck_F_rewind(&d);
			if (rc)
				goto yield;
			do {
				fsl_deck_F_next(&d, &cf);
				if (cf && !fsl_strcmp(cf->name, path)) {
					xminus = fsl_strdup(cf->uuid);
					if (xminus == NULL) {
						RC(FSL_RC_ERROR, "%s",
						    "fsl_strdup");
						goto yield;
					}
					fid = fsl_uuid_to_rid(f, xminus);
					break;
				}
			} while (cf);
			fsl_deck_finalize(&d);
		}
		if (!xminus)
			xminus = fsl_strdup(NULL_DEVICE);
		allow_symlinks = fsl_config_get_bool(f, FSL_CONFDB_REPO, false,
		    "allow-symlinks");
		if (!symlink != !(fsl_is_symlink(fsl_buffer_cstr(&abspath)) &&
		    allow_symlinks)) {
			rc = write_diff_meta(buf, path, xminus, path,
			    NULL_DEVICE, diff_flags, change);
			fsl_buffer_append(buf, "\nSymbolic links and regular "
			    "files cannot be diffed\n", -1);
			if (rc)
				goto yield;
			continue;
		}
		if (fid > 0 && change != FSL_CKOUT_CHANGE_ADDED) {
			rc = fsl_content_get(f, fid, &bminus);
			if (rc)
				goto yield;
		} else
			fsl_buffer_clear(&bminus);
		if (paths != NULL && !TAILQ_EMPTY(paths)) {
			struct fnc_pathlist_entry *pe;
			diff = false;
			TAILQ_FOREACH(pe, paths, entry)
				if (!fsl_strncmp(pe->path, path, pe->pathlen)
				    || !fsl_strcmp(pe->path, path)) {
					diff = true;
					break;
				}
		}
		if (diff)
			rc = diff_file(buf, &bminus, path, xminus,
			    fsl_buffer_cstr(&abspath), change, diff_flags,
			    context, sbs);
		fsl_buffer_reuse(&bminus);
		fsl_buffer_reuse(&abspath);
		fsl_free(xminus);
		xminus = NULL;
		if (rc == FSL_RC_RANGE) {
			fsl_buffer_append(buf,
			    "\nDiff has too many changes\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc == FSL_RC_DIFF_BINARY) {
			fsl_buffer_append(buf,
			    "\nBinary files cannot be diffed\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc)
			goto yield;
	}

yield:
	fsl_stmt_finalize(st);
	fsl_free(xminus);
unload:
	fsl_vfile_unload_except(f, cid);
	fsl_buffer_clear(&abspath);
	fsl_buffer_clear(&bminus);
	fsl_buffer_clear(&sql);
	return rc;
}

/*
 * Write diff index line and file metadata (i.e., file paths and hashes), which
 * signify file addition, removal, or modification.
 *   buf         output buffer in which diff output will be appended
 *   zminus      file name of the file being diffed against
 *   xminus      hex hash of file named zminus
 *   zplus       file name of the file being diffed
 *   xplus       hex hash of the file named zplus
 *   diff_flags  bitwise flags to control the diff
 *   change      enum denoting the versioning change of the file
 */
static int
write_diff_meta(fsl_buffer *buf, const char *zminus, fsl_uuid_str xminus,
    const char *zplus, fsl_uuid_str xplus, int diff_flags,
    enum fsl_ckout_change_e change)
{
	int	rc = 0;
	const char	*index, *plus, *minus;

	index = zplus ? zplus : (zminus ? zminus : NULL_DEVICE);

	switch (change) {
	case FSL_CKOUT_CHANGE_MERGE_ADD:
		/* FALL THROUGH */
	case FSL_CKOUT_CHANGE_INTEGRATE_ADD:
		/* FALL THROUGH */
	case FSL_CKOUT_CHANGE_ADDED:
		minus = NULL_DEVICE;
		plus = xplus;
		zminus = NULL_DEVICE;
		break;
	case FSL_CKOUT_CHANGE_MISSING:
		/* FALL THROUGH */
	case FSL_CKOUT_CHANGE_REMOVED:
		minus = xminus;
		plus = NULL_DEVICE;
		zplus = NULL_DEVICE;
		break;
	case FSL_CKOUT_CHANGE_RENAMED:
		/* FALL THROUGH */
	case FSL_CKOUT_CHANGE_MOD:
		/* FALL THROUGH */
	default:
		minus = xminus;
		plus = xplus;
		break;
	}

	if (diff_flags & FSL_DIFF_INVERT) {
		const char *tmp = minus;
		minus = plus;
		plus = tmp;
		tmp = zminus;
		zminus = zplus;
		zplus = tmp;
	}

	if ((diff_flags & (FSL_DIFF_SIDEBYSIDE | FSL_DIFF_BRIEF)) == 0) {
		rc = fsl_buffer_appendf(buf, "\nIndex: %s\n%.71c\n", index, '=');
		if (!rc)
			rc = fsl_buffer_appendf(buf, "hash - %s\nhash + %s\n",
			    minus, plus);
	}
	if (!rc && (diff_flags & FSL_DIFF_BRIEF) == 0)
		rc = fsl_buffer_appendf(buf, "--- %s\n+++ %s\n", zminus, zplus);

	return rc;
}

/*
 * The diff_file_artifact() counterpart that diffs actual files on disk rather
 * than file artifacts in the Fossil repository's blob table.
 *   buf      output buffer in which diff output will be appended
 *   bminus   blob containing content of the versioned file being diffed against
 *   zminus   filename of bminus
 *   xminus   hex UUID containing the SHA{1,3} hash of the file named zminus
 *   abspath  absolute path to the file on disk being diffed
 *   change   enum denoting the versioning change of the file
 * diff_flags, context, and sbs are the same parameters as diff_file_artifact()
 */
static int
diff_file(fsl_buffer *buf, fsl_buffer *bminus, const char *zminus,
    fsl_uuid_str xminus, const char *abspath, enum fsl_ckout_change_e change,
    int diff_flags, int context, bool sbs)
{
	fsl_cx		*f = fcli_cx();
	fsl_buffer	 bplus = fsl_buffer_empty;
	fsl_buffer	 xplus = fsl_buffer_empty;
	const char	*zplus = NULL;
	int		 rc = 0;
	bool		 verbose;

	/*
	 * If it exists, read content of abspath to diff EXCEPT for the content
	 * of 'fossil rm FILE' files because they will either: (1) have the same
	 * content as the versioned file's blob in bminus or (2) have changes.
	 * As a result, the upcoming call to fsl_diff_text_to_buffer() _will_
	 * (1) produce an empty diff or (2) show the differences; neither are
	 * expected behaviour because the SCM has been instructed to remove the
	 * file; therefore, the diff should display the versioned file content
	 * as being entirely removed. With this check, fnc now contrasts the
	 * behaviour of fossil(1), which produces the abovementioned unexpected
	 * output described in (1) and (2).
	 */
	if (change != FSL_CKOUT_CHANGE_REMOVED) {
		rc = fsl_ckout_file_content(f, false, abspath, &bplus);
		if (rc)
			goto end;
		/*
		 * To replicate fossil(1)'s behaviour—where a fossil rm'd file
		 * will either show as an unchanged or edited rather than a
		 * removed file with 'fossil diff -v' output—remove the above
		 * 'if (change != FSL_CKOUT_CHANGE_REMOVED)' from the else
		 * condition and uncomment the following three lines of code.
		 */
		/* if (change == FSL_CKOUT_CHANGE_REMOVED && */
		/*     !fsl_buffer_compare(bminus, &bplus)) */
		/*	fsl_buffer_clear(&bplus); */
		zplus = zminus;
	}

	switch (fsl_strlen(xminus)) {
	case FSL_STRLEN_K256:
		rc = fsl_sha3sum_buffer(&bplus, &xplus);
		break;
	case FSL_STRLEN_SHA1:
		rc = fsl_sha1sum_buffer(&bplus, &xplus);
		break;
	case NULL_DEVICELEN:
		switch (fsl_config_get_int32(f, FSL_CONFDB_REPO,
		    FSL_HPOLICY_AUTO, "hash-policy")) {
		case FSL_HPOLICY_SHA1:
			rc = fsl_sha1sum_buffer(&bplus, &xplus);
			break;
		case FSL_HPOLICY_AUTO:
			/* FALL THROUGH */
		case FSL_HPOLICY_SHA3:
			/* FALL THROUGH */
		case FSL_HPOLICY_SHA3_ONLY:
			rc = fsl_sha3sum_buffer(&bplus, &xplus);
			break;
		}
		break;
	default:
		RC(FSL_RC_SIZE_MISMATCH, "invalid artifact uuid [%s]", xminus);
		goto end;
	}
	if (rc)
		goto end;

	rc = write_diff_meta(buf, zminus, xminus, zplus, fsl_buffer_str(&xplus),
	    diff_flags, change);
	if (rc)
		goto end;

	verbose = (diff_flags & FSL_DIFF_VERBOSE) != 0 ? true : false;
	if (diff_flags & FSL_DIFF_BRIEF) {
		rc = fsl_buffer_compare(bminus, &bplus);
		if (!rc)
			rc = fsl_buffer_appendf(buf, "CHANGED -> %s\n", zminus);
	} else if (verbose || (bminus->used && bplus.used)) {
		rc = fsl_diff_text_to_buffer(bminus, &bplus, buf, context,
		    sbs, diff_flags);
	}

end:
	fsl_buffer_clear(&bplus);
	fsl_buffer_clear(&xplus);

	return rc;
}

/*
 * Parse the deck of non-checkin commits to present a 'fossil ui' equivalent
 * of the corresponding artifact when selected from the timeline.
 * TODO: Rename this horrible function name.
 */
static int
diff_non_checkin(fsl_buffer *buf, struct fnc_commit_artifact *commit,
    int diff_flags, int context, int sbs)
{
	fsl_cx		*f = fcli_cx();
	fsl_buffer	 wiki = fsl_buffer_empty;
	fsl_buffer	 pwiki = fsl_buffer_empty;
	fsl_id_t	 prid = 0;
	fsl_size_t	 idx;
	int		 rc = 0;

	fsl_deck *d = NULL;
	d = fsl_deck_malloc();
	if (d == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_deck_malloc");

	fsl_deck_init(f, d, FSL_SATYPE_ANY);
	if ((rc = fsl_deck_load_rid(f, d, commit->rid, FSL_SATYPE_ANY)))
		goto end;

	/*
	 * Present ticket commits as a series of field: value tuples as per
	 * the Fossil UI /info/UUID view.
	 */
	if (d->type == FSL_SATYPE_TICKET) {
		for (idx = 0; idx < d->J.used; ++idx) {
			fsl_card_J *ticket = d->J.list[idx];
			bool icom = !fsl_strncmp(ticket->field, "icom", 4);
			fsl_buffer_appendf(buf, "%d. %s:%s%s%c\n", idx + 1,
			    ticket->field, icom ? "\n\n" : " ", ticket->value,
			    icom ? '\n' : ' ');
		}
		goto end;
	}

	if (d->type == FSL_SATYPE_CONTROL) {
		for (idx = 0; idx < d->T.used; ++idx) {
			fsl_card_T *ctl = d->T.list[idx];
			fsl_buffer_appendf(buf, "Tag %d ", idx + 1);
			switch (ctl->type) {
			case FSL_TAGTYPE_CANCEL:
				fsl_buffer_append(buf, "[CANCEL]", -1);
				break;
			case FSL_TAGTYPE_ADD:
				fsl_buffer_append(buf, "[ADD]", -1);
				break;
			case FSL_TAGTYPE_PROPAGATING:
				fsl_buffer_append(buf, "[PROPAGATE]", -1);
				break;
			default:
				break;
			}
			if (ctl->uuid)
				fsl_buffer_appendf(buf, "\ncheckin %s",
				    ctl->uuid);
			fsl_buffer_appendf(buf, "\n%s", ctl->name);
			if (!fsl_strcmp(ctl->name, "branch"))
				commit->branch = fsl_strdup(ctl->value);
			if (ctl->value)
				fsl_buffer_appendf(buf, " -> %s", ctl->value);
			fsl_buffer_append(buf, "\n\n", 2);
		}
		goto end;
	}
	/*
	 * If neither a ticket nor control artifact, we assume it's a wiki, so
	 * check if it has a parent commit to diff against. If not, append the
	 * entire wiki card content.
	 */
	fsl_buffer_append(&wiki, d->W.mem, d->W.used);
	if (commit->puuid == NULL) {
		if (d->P.used > 0)
			commit->puuid = fsl_strdup(d->P.list[0]);
		else {
			fsl_buffer_copy(&wiki, buf);
			goto end;
		}
	}

	/* Diff the artifacts if a parent is found. */
	if ((rc = fsl_sym_to_rid(f, commit->puuid, FSL_SATYPE_ANY, &prid)))
		goto end;
	if ((rc = fsl_deck_load_rid(f, d, prid, FSL_SATYPE_ANY)))
		goto end;
	fsl_buffer_append(&pwiki, d->W.mem, d->W.used);

	rc = fsl_diff_text_to_buffer(&pwiki, &wiki, buf, context, sbs,
	    diff_flags);

	/* If a technote, provide the full content after its diff. */
	if (d->type == FSL_SATYPE_TECHNOTE)
		fsl_buffer_appendf(buf, "\n---\n\n%s", wiki.mem);

end:
	fsl_buffer_clear(&wiki);
	fsl_buffer_clear(&pwiki);
	fsl_deck_finalize(d);
	return rc;
}

/*
 * Compute the differences between two repository file artifacts to produce the
 * set of changes necessary to convert one into the other.
 *   buf         output buffer in which diff output will be appended
 *   vid1        repo record id of the version from which artifact a belongs
 *   a           file artifact being diffed against
 *   vid2        repo record id of the version from which artifact b belongs
 *   b           file artifact being diffed
 *   change      enum denoting the versioning change of the file
 *   diff_flags  bitwise flags to control the diff
 *   context     the number of context lines to surround changes
 *   sbs	 number of columns in which to display each side-by-side diff
 */
static int
diff_file_artifact(fsl_buffer *buf, fsl_id_t vid1, const fsl_card_F *a,
    fsl_id_t vid2, const fsl_card_F *b, enum fsl_ckout_change_e change,
    int diff_flags, int context, int sbs, enum fnc_diff_type diff_type)
{
	fsl_cx		*f = fcli_cx();
	fsl_stmt	 stmt = fsl_stmt_empty;
	fsl_buffer	 fbuf1 = fsl_buffer_empty;
	fsl_buffer	 fbuf2 = fsl_buffer_empty;
	char		*zminus0 = NULL, *zplus0 = NULL;
	const char	*zplus = NULL, *zminus = NULL;
	fsl_uuid_str	 xplus0 = NULL, xminus0 = NULL;
	fsl_uuid_str	 xplus = NULL, xminus = NULL;
	int		 rc = 0;
	bool		 verbose;

	assert(vid1 != vid2);
	assert(vid2 > 0 &&
	    "local checkout should be diffed with diff_checkout()");

	fbuf2.used = fbuf1.used = 0;

	if (a) {
		rc = fsl_card_F_content(f, a, &fbuf1);
		if (rc)
			goto end;
		zminus = a->name;
		xminus = a->uuid;
	} else if (diff_type == FNC_DIFF_BLOB) {
		rc = fsl_cx_prepare(f, &stmt,
		    "SELECT name FROM filename, mlink "
		    "WHERE filename.fnid=mlink.fnid AND mlink.fid = %d", vid1);
		if (rc) {
			rc = RC(FSL_RC_DB, "%s %d", "fsl_cx_prepare", vid1);
			goto end;
		}
		rc = fsl_stmt_step(&stmt);
		if (rc == FSL_RC_STEP_ROW) {
			rc = 0;
			zminus0 = fsl_strdup(fsl_stmt_g_text(&stmt, 0, NULL));
			zminus = zminus0;
		} else if (rc == FSL_RC_STEP_DONE)
			rc = 0;
		else if (rc) {
			rc = RC(rc, "%s", "fsl_stmt_step");
			goto end;
		}
		xminus0 = fsl_rid_to_uuid(f, vid1);
		xminus = xminus0;
		fsl_stmt_finalize(&stmt);
		fsl_content_get(f, vid1, &fbuf1);
	}
	if (b) {
		rc = fsl_card_F_content(f, b, &fbuf2);
		if (rc)
			goto end;
		zplus = b->name;
		xplus = b->uuid;
	} else if (diff_type == FNC_DIFF_BLOB) {
		rc = fsl_cx_prepare(f, &stmt,
		    "SELECT name FROM filename, mlink "
		    "WHERE filename.fnid=mlink.fnid AND mlink.fid = %d", vid2);
		if (rc) {
			rc = RC(FSL_RC_DB, "%s %d", "fsl_cx_prepare", vid2);
			goto end;
		}
		rc = fsl_stmt_step(&stmt);
		if (rc == FSL_RC_STEP_ROW) {
			rc = 0;
			zplus0 = fsl_strdup(fsl_stmt_g_text(&stmt, 0, NULL));
			zplus = zplus0;
		} else if (rc == FSL_RC_STEP_DONE)
			rc = 0;
		else if (rc) {
			rc = RC(rc, "%s", "fsl_stmt_step");
			goto end;
		}
		xplus0 = fsl_rid_to_uuid(f, vid2);
		xplus = xplus0;
		fsl_stmt_finalize(&stmt);
		fsl_content_get(f, vid2, &fbuf2);
	}

	rc = write_diff_meta(buf, zminus, xminus, zplus, xplus, diff_flags,
	    change);
	verbose = (diff_flags & FSL_DIFF_VERBOSE) != 0 ? true : false;
	if (verbose || (a && b))
		rc = fsl_diff_text_to_buffer(&fbuf1, &fbuf2, buf, context, sbs,
		    diff_flags);
	if (rc)
		RC(rc, "%s: fsl_diff_text_to_buffer\n"
		    " -> %s [%s]\n -> %s [%s]", fsl_rc_cstr(rc),
		    a ? a->name : NULL_DEVICE, a ? a->uuid : NULL_DEVICE,
		    b ? b->name : NULL_DEVICE, b ? b->uuid : NULL_DEVICE);
end:
	fsl_free(zminus0);
	fsl_free(zplus0);
	fsl_free(xminus0);
	fsl_free(xplus0);
	fsl_buffer_clear(&fbuf1);
	fsl_buffer_clear(&fbuf2);
	return rc;
}

static int
show_diff(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	char				*headln, *id2, *id1 = NULL;

	/* Some diffs (e.g., technote, tag) have no parent hash to display. */
	id1 = fsl_strdup(s->id1 ? s->id1 : "/dev/null");
	if (id1 == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");

	/*
	 * If diffing the work tree, we have no hash to display for it.
	 * XXX Display "work tree" or "checkout" or "/dev/null" for clarity?
	 */
	id2 = fsl_strdup(s->id2 ? s->id2 : "");
	if (id2 == NULL) {
		fsl_free(id1);
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	}

	if ((headln = fsl_mprintf("diff %.40s %.40s", id1, id2)) == NULL) {
		fsl_free(id1);
		fsl_free(id2);
		return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
	}

	fsl_free(id1);
	fsl_free(id2);
	return write_diff(view, headln);
}

static int
write_diff(struct fnc_view *view, char *headln)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	regmatch_t			*regmatch = &view->regmatch;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	char				*line;
	size_t				 linesz = 0;
	ssize_t				 linelen;
	off_t				 line_offset;
	int				 wstrlen;
	int				 max_lines = view->nlines;
	int				 nlines = s->nlines;
	int				 rc = 0, nprintln = 0;
	int				 match = -1;

	line_offset = s->line_offsets[s->first_line_onscreen - 1];
	if (fseeko(s->f, line_offset, SEEK_SET))
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "fseeko");

	werase(view->window);

	if (headln) {
		if ((line = fsl_mprintf("[%d/%d] %s", (s->first_line_onscreen -
		    1 + s->current_line), nlines, headln)) == NULL)
			return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0);
		fsl_free(line);
		fsl_free(headln);
		if (rc)
			return rc;

		if (screen_is_shared(view))
			wstandout(view->window);
		waddwstr(view->window, wcstr);
		fsl_free(wcstr);
		wcstr = NULL;
		if (screen_is_shared(view))
			wstandend(view->window);
		if (wstrlen <= view->ncols - 1)
			waddch(view->window, '\n');

		if (max_lines <= 1)
			return rc;
		--max_lines;
	}

	s->eof = false;
	line = NULL;
	while (max_lines > 0 && nprintln < max_lines) {
		linelen = getline(&line, &linesz, s->f);
		if (linelen == -1) {
			if (feof(s->f)) {
				s->eof = true;
				break;
			}
			fsl_free(line);
			RC(ferror(s->f) ? fsl_errno_to_rc(errno, FSL_RC_IO) :
			    FSL_RC_IO, "%s", "getline");
			return rc;
		}

		if (s->colour && (match = fsl_list_index_of(&s->colours, line,
		    match_line)) != -1)
			c = s->colours.list[match];
		if (c)
			wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
		if (s->first_line_onscreen + nprintln == s->matched_line &&
		    regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
			rc = write_matched_line(&wstrlen, line, view->ncols, 0,
			    view->window, regmatch);
			if (rc) {
				fsl_free(line);
				return rc;
			}
		} else {
			rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0);
			if (rc) {
				fsl_free(line);
				return rc;
			}
			waddwstr(view->window, wcstr);
			fsl_free(wcstr);
			wcstr = NULL;
		}
		if (c) {
			wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
			c = NULL;
		}
		if (wstrlen <= view->ncols - 1)
			waddch(view->window, '\n');
		++nprintln;
	}
	fsl_free(line);
	if (nprintln >= 1)
		s->last_line_onscreen = s->first_line_onscreen + (nprintln - 1);
	else
		s->last_line_onscreen = s->first_line_onscreen;

	draw_vborder(view);

	if (s->eof) {
		while (nprintln < view->nlines) {
			waddch(view->window, '\n');
			++nprintln;
		}

		wstandout(view->window);
		waddstr(view->window, "(END)");
		wstandend(view->window);
	}

	return rc;
}

static int
match_line(const void *ln, const void *key)
{
	struct fnc_colour *c = (struct fnc_colour *)key;
	const char *line = ln;

	return regexec(&c->regex, line, 0, NULL, 0);
}

static bool
screen_is_shared(struct fnc_view *view)
{
	if (view_is_parent(view)) {
		if (view->child == NULL || view->child->active ||
		    !screen_is_split(view->child))
			return false;
	} else if (!screen_is_split(view))
		return false;

	return view->active;
}

static int
view_is_parent(struct fnc_view *view)
{
	return view->parent == NULL;
}

static int
screen_is_split(struct fnc_view *view)
{
	return view->start_col > 0;
}

static int
write_matched_line(int *col_pos, const char *line, int ncols_avail,
    int start_column, WINDOW *window, regmatch_t *regmatch)
{
	wchar_t		*wcstr;
	char		*s;
	int		 wstrlen;
	int		 rc = 0;

	*col_pos = 0;

	/* Copy the line up to the matching substring & write it to screen. */
	s = fsl_strndup(line, regmatch->rm_so);
	if (s == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strndup");

	rc = formatln(&wcstr, &wstrlen, s, ncols_avail, start_column);
	if (rc) {
		free(s);
		return rc;
	}
	waddwstr(window, wcstr);
	free(wcstr);
	free(s);
	ncols_avail -= wstrlen;
	*col_pos += wstrlen;

	/* If not EOL, copy matching string & write to screen with highlight. */
	if (ncols_avail > 0) {
		s = fsl_strndup(line + regmatch->rm_so,
		    regmatch->rm_eo - regmatch->rm_so);
		if (s == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strndup");
			free(s);
			return rc;
		}
		rc = formatln(&wcstr, &wstrlen, s, ncols_avail, start_column);
		if (rc) {
			free(s);
			return rc;
		}
		wattr_on(window, A_REVERSE, NULL);
		waddwstr(window, wcstr);
		wattr_off(window, A_REVERSE, NULL);
		free(wcstr);
		free(s);
		ncols_avail -= wstrlen;
		*col_pos += wstrlen;
	}

	/* Write the rest of the line if not yet at EOL. */
	if (ncols_avail > 0 && fsl_strlen(line) > (fsl_size_t)regmatch->rm_eo) {
		rc = formatln(&wcstr, &wstrlen, line + regmatch->rm_eo,
		    ncols_avail, start_column);
		if (rc)
			return rc;
		waddwstr(window, wcstr);
		free(wcstr);
		*col_pos += wstrlen;
	}

	return rc;
}

static void
draw_vborder(struct fnc_view *view)
{
	const struct fnc_view	*view_above;
	char			*codeset = nl_langinfo(CODESET);
	PANEL			*panel;

	if (view->parent)
		draw_vborder(view->parent);

	panel = panel_above(view->panel);
	if (panel == NULL)
		return;

	view_above = panel_userptr(panel);
	mvwvline(view->window, view->start_ln, view_above->start_col - 1,
	    (strcmp(codeset, "UTF-8") == 0) ? ACS_VLINE : '|', view->nlines);
#ifdef __linux__
	wnoutrefresh(view->window);
#endif
}

static int
diff_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	struct fnc_tl_view_state	*tlstate;
	struct commit_entry		*previous_selection;
	char				*line = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 i, rc = 0;
	bool				 tl_down = false;

	switch (ch) {
	case KEY_DOWN:
	case 'j':
		if (!s->eof)
			++s->first_line_onscreen;
		break;
	case KEY_NPAGE:
	case CTRL('f'):
	case ' ':
		if (s->eof)
			break;
		i = 0;
		while (!s->eof && i++ < view->nlines - 1) {
			linelen = getline(&line, &linesz, s->f);
			++s->first_line_onscreen;
			if (linelen == -1) {
				if (feof(s->f))
					s->eof = true;
				else
					RC(ferror(s->f) ?
					    fsl_errno_to_rc(errno, FSL_RC_IO) :
					    FSL_RC_IO, "%s", "getline");
				break;
			}
		}
		free(line);
		break;
	case KEY_END:
	case 'G':
		if (s->eof)
			break;
		s->first_line_onscreen = (s->nlines - view->nlines) + 2;
		s->eof = true;
		break;
	case KEY_UP:
	case 'k':
		if (s->first_line_onscreen > 1)
			--s->first_line_onscreen;
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->first_line_onscreen == 1)
			break;
		i = 0;
		while (i++ < view->nlines - 1 && s->first_line_onscreen > 1)
			--s->first_line_onscreen;
		break;
	case 'g':
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	case KEY_HOME:
		s->first_line_onscreen = 1;
		break;
	case 'c':
	case 'i':
	case 'v':
	case 'w':
		if (ch == 'c')
			s->colour = !s->colour;
		if (ch == 'i')
			s->diff_flags ^= FSL_DIFF_INVERT;
		if (ch == 'v')
			s->diff_flags ^= FSL_DIFF_VERBOSE;
		if (ch == 'w')
			s->diff_flags ^= FSL_DIFF_IGNORE_ALLWS;
		wclear(view->window);
		s->first_line_onscreen = 1;
		s->last_line_onscreen = view->nlines;
		show_diff_status(view);
		rc = create_diff(s);
		break;
	case '-':
	case '_':
		if (s->context > 0) {
			--s->context;
			show_diff_status(view);
			rc = create_diff(s);
			if (s->first_line_onscreen + view->nlines - 1 >
			    (int)s->nlines) {
				s->first_line_onscreen = 1;
				s->last_line_onscreen = view->nlines;
			}
		}
		break;
	case '+':
	case '=':
		if (s->context < DIFF_MAX_CTXT) {
			++s->context;
			show_diff_status(view);
			rc = create_diff(s);
		}
		break;
	case CTRL('j'):
	case '>':
	case '.':
	case 'J':
		tl_down = true;
		/* FALL THROUGH */
	case CTRL('k'):
	case '<':
	case ',':
	case 'K':
		if (s->timeline_view == NULL)
			break;
		tlstate = &s->timeline_view->state.timeline;
		previous_selection = tlstate->selected_commit;

		if ((rc = tl_input_handler(NULL, s->timeline_view,
		    tl_down ? KEY_DOWN : KEY_UP)))
			break;

		if (previous_selection == tlstate->selected_commit)
			break;

		if ((rc = set_selected_commit(s, tlstate->selected_commit)))
			break;

		s->first_line_onscreen = 1;
		s->last_line_onscreen = view->nlines;

		show_diff_status(view);
		rc = create_diff(s);
		break;
	default:
		break;
	}

	return rc;
}

static int
set_selected_commit(struct fnc_diff_view_state *s, struct commit_entry *entry)
{
	fsl_free(s->id2);
	s->id2 = fsl_strdup(entry->commit->uuid);
	if (s->id2 == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	fsl_free(s->id1);
	s->id1 = entry->commit->puuid ? fsl_strdup(entry->commit->puuid) : NULL;
	s->selected_commit = entry->commit;

	return 0;
}

static int
diff_search_init(struct fnc_view *view)
{
	struct fnc_diff_view_state *s = &view->state.diff;

	s->matched_line = 0;
	return 0;
}

static int
diff_search_next(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	char				*line = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 start_ln;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
		return 0;
	}

	if (s->matched_line) {
		if (view->searching == SEARCH_FORWARD)
			start_ln = s->matched_line + 1;
		else
			start_ln = s->matched_line - 1;
	} else {
		if (view->searching == SEARCH_FORWARD)
			start_ln = 1;
		else
			start_ln = s->nlines;
	}

	while (1) {
		off_t offset;

		if (start_ln <= 0 || start_ln > (int)s->nlines) {
			if (s->matched_line == 0) {
				view->search_status = SEARCH_CONTINUE;
				break;
			}

			if (view->searching == SEARCH_FORWARD)
				start_ln = 1;
			else
				start_ln = s->nlines;
		}

		offset = s->line_offsets[start_ln - 1];
		if (fseeko(s->f, offset, SEEK_SET) != 0) {
			free(line);
			return RC(fsl_errno_to_rc(errno, FSL_RC_IO),
			    "%s", "fseeko");
		}
		linelen = getline(&line, &linesz, s->f);
		if (linelen != -1 && regexec(&view->regex, line, 1,
		    &view->regmatch, 0) == 0) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_line = start_ln;
			break;
		}
		if (view->searching == SEARCH_FORWARD)
			++start_ln;
		else
			--start_ln;
	}
	free(line);

	if (s->matched_line) {
		s->first_line_onscreen = s->matched_line;
		s->current_line = 1;
	}

	return 0;
}

static int
close_diff_view(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	struct fsl_list_state		st = { FNC_COLOUR_OBJ };
	int				 rc = 0;

	if (s->f && fclose(s->f) == EOF)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");
	fsl_free(s->id1);
	s->id1 = NULL;
	fsl_free(s->id2);
	s->id2 = NULL;
	fsl_free(s->line_offsets);
	fsl_list_clear(&s->colours, fsl_list_object_free, &st);
	s->line_offsets = NULL;
	s->nlines = 0;
	return rc;
}

static void
fnc_resizeterm(void)
{
	struct winsize	size;
	int		cols, lines;

	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
		cols = 80;
		lines = 24;
	} else {
		cols = size.ws_col;
		lines = size.ws_row;
	}
	resize_term(lines, cols);
}

static int
view_resize(struct fnc_view *view)
{
	int	 nlines, ncols;

	if (view->lines > LINES)
		nlines = view->nlines - (view->lines - LINES);
	else
		nlines = view->nlines + (LINES - view->lines);

	if (view->cols > COLS)
		ncols = view->ncols - (view->cols - COLS);
	else
		ncols = view->ncols + (COLS - view->cols);

	if (wresize(view->window, nlines, ncols) == ERR)
		return RC(FSL_RC_ERROR, "%s", "wresize");
	if (replace_panel(view->panel, view->window) == ERR)
		return RC(FSL_RC_ERROR, "%s", "replace_panel");
	wclear(view->window);

	view->nlines = nlines;
	view->ncols = ncols;
	view->lines = LINES;
	view->cols = COLS;

	if (view->child) {
		view->child->start_col = view_split_start_col(view->start_col);
		if (view->child->start_col == 0) {
			make_fullscreen(view->child);
			if (view->child->active)
				show_panel(view->child->panel);
			else
				show_panel(view->panel);
		} else {
			make_splitscreen(view->child);
			show_panel(view->child->panel);
		}
	}

	return 0;
}

/*
 * Consume repeatable arguments containing artifact type values used in
 * constructing the SQL query to generate commit records of the specified
 * type for the timeline. TODO: Enhance this to generalise processing of
 * various repeatable arguments--paths, usernames, branches, etc.--so we
 * can filter on multiples of these values.
 */
static int
fcli_flag_type_arg_cb(fcli_cliflag const *v)
{
	if (fnc_init.filter_types->nitems)
		fnc_init.filter_types->values =
		    fsl_realloc(fnc_init.filter_types->values,
		    (fnc_init.filter_types->nitems + 1) * sizeof(char *));
	fnc_init.filter_types->values[fnc_init.filter_types->nitems++] =
	    *((const char **)v->flagValue);

	return FCLI_RC_FLAG_AGAIN;
}

static void
sigwinch_handler(int sig)
{
	if (sig == SIGWINCH) {
		struct winsize winsz;

		ioctl(0, TIOCGWINSZ, &winsz);
		rec_sigwinch = 1;
	}
}

static void
sigpipe_handler(int sig)
{
	struct sigaction	sact;
	int			e;

	rec_sigpipe = 1;
	memset(&sact, 0, sizeof(sact));
	sact.sa_handler = SIG_IGN;
	sact.sa_flags = SA_RESTART;
	e = sigaction(SIGPIPE, &sact, NULL);
	if (e)
		err(1, "SIGPIPE");
}

static void
sigcont_handler(int sig)
{
	rec_sigcont = 1;
}

__dead static void
usage(void)
{
	/*
	 * It looks like the fsl_cx f member of the ::fcli singleton has
	 * already been cleaned up by the time this wrapper is called from
	 * fcli_help() after hijacking the process whenever the '--help'
	 * argument is passsed on the command line, so we can't use the
	 * f->output fsl_outputer implementation as we would like.
	 */
	/* fsl_cx *f = fcli_cx(); */
	/* f->output = fsl_outputer_FILE; */
	/* f->output.state.state = (fnc_init.err == true) ? stderr : stdout; */
        FILE *f = fnc_init.err ? stderr : stdout;
	size_t idx = 0;

	endwin();

	/* If a command was passed on the CLI, output its corresponding help. */
	if (fnc_init.cmdarg)
		for (idx = 0; idx < nitems(fnc_init.cmd_args); ++idx) {
			fcli_command cmd = fnc_init.cmd_args[idx];
			if (!fsl_strcmp(fnc_init.cmdarg, cmd.name) ||
			    fcli_cmd_aliascmp(&cmd, fnc_init.cmdarg)) {
				fcli_command_help(&cmd, true, true);
				exit(fcli_end_of_main(fnc_init.err));
			}
		}

	/* Otherwise, output help/usage for all commands. */
	fcli_command_help(fnc_init.cmd_args, true, false);
	fsl_fprintf(f, "  note: %s "
	    "with no args defaults to the timeline command.\n\n",
	    fcli_progname());

	exit(fcli_end_of_main(fnc_init.err));
}

static void
usage_timeline(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s timeline [-C|--no-colour] [-T tag] [-b branch] "
	    "[-c commit] [-h|--help] [-n n] [-t type] [-u user] [-z|--utc] "
	    "[path]\n"
	    "  e.g.: %s timeline --type ci -u jimmy src/frobnitz.c\n\n",
	    fcli_progname(), fcli_progname());
}

static void
usage_diff(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s diff [-C|--no-colour] [-h|--help] [-i|--invert]"
	    " [-q|--quiet] [-w|--whitespace] [-x|--context n] "
	    "[artifact1 [artifact2]] [path ...]\n  "
	    "e.g.: %s diff --context 3 d34db33f c0ff33 src/*.c\n\n",
	    fcli_progname(), fcli_progname());
}

static void
usage_tree(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s tree [-C|--no-colour] [-c commit] [-h|--help] [path]\n"
	    "  e.g.: %s tree -c d34dc0d3\n\n" ,
	    fcli_progname(), fcli_progname());
}

static void
usage_blame(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s blame [-C|--no-colour] [-c commit [-r]] [-h|--help] "
	    "[-n n] path\n"
	    "  e.g.: %s blame -c d34db33f src/foo.c\n\n" ,
	    fcli_progname(), fcli_progname());
}

static void
usage_branch(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s branch [-C|--no-colour] [-a|--after date] "
	    "[-b|--before date] [-c|--closed] [-h|--help] [-o|--open] "
	    "[-p|--no-private] [-r|--reverse] [-s|--sort order] [glob]\n"
	    "  e.g.: %s branch -b 2020-10-10\n\n" ,
	    fcli_progname(), fcli_progname());
}

static int
cmd_diff(fcli_command const *argv)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_view			*view;
	struct fnc_commit_artifact	*commit = NULL;
	struct fnc_pathlist_head	 paths;
	struct fnc_pathlist_entry	*pe;
	fsl_deck			 d = fsl_deck_empty;
	fsl_stmt			*q = NULL;
	const char			*artifact1 = NULL, *artifact2 = NULL;
	char				*path0 = NULL;
	fsl_id_t			 prid = -1, rid = -1;
	int				 context = DIFF_DEF_CTXT, rc = 0;
	unsigned short			 blob = 0;
	enum fnc_diff_type		 diff_type;
	bool				 showmeta = false;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	TAILQ_INIT(&paths);

	/*
	 * To provide an intuitive UI, use some magic. First, if there's an arg
	 * and it's a symbolic checkin name, take as a checkin artifact. Repeat
	 * for the next arg. If just one is a checkin, diff changes on disk
	 * against it. If neither are checkins, diff changes on disk against the
	 * current checkout. If both are checkins, diff against eachother. Treat
	 * any non-symbol args as paths and try map to a valid repo path or F
	 * card in the checkin(s) deck(s). It's tricky, but provides a smart UI:
	 * fnc diff f1 f2 ... -> diff f{1,2,...} on disk against current ckout
	 * fnc diff sym3 f1 -> diff f1 on disk against f1 found in checkin sym3
	 * fnc diff sym1 sym2 f1 f2 -> diff f{1,2} between checkins sym1 & sym2
	 */
	if (!fsl_sym_to_rid(f, fcli_next_arg(false), FSL_SATYPE_ANY, &prid)) {
		artifact1 = fcli_next_arg(true);
		if (!fsl_rid_is_a_checkin(f, prid)) {
			if (fsl_rid_to_artifact_uuid(f, prid, FSL_SATYPE_ANY)
			    != NULL) {
				rc = RC(FSL_RC_TYPE,
				    "artifact [%s] not resolvable to a checkin",
				    artifact1);
				goto end;
			}
			++blob;
		}
		if (!fsl_sym_to_rid(f, fcli_next_arg(false), FSL_SATYPE_ANY,
		    &rid)) {
			artifact2 = fcli_next_arg(true);
			diff_type = FNC_DIFF_COMMIT;
			if (!fsl_rid_is_a_checkin(f, rid)) {
				if (fsl_rid_to_artifact_uuid(f,
				    prid, FSL_SATYPE_ANY) != NULL) {
					rc = RC(FSL_RC_TYPE, "artifact [%s] "
					    "not resolvable to a checkin",
					    artifact2);
					goto end;
				}
				++blob;
			}
		}
	}
	if (fcli_error()->code == FSL_RC_NOT_FOUND) {
		fcli_err_reset();  /* If args aren't symbols, treat as paths. */
		rc = 0;
	}
	if (blob == 2)
		diff_type = FNC_DIFF_BLOB;
	if (!artifact1 && diff_type != FNC_DIFF_BLOB) {
		artifact1 = "current";
		rc = fsl_sym_to_rid(f, artifact1, FSL_SATYPE_CHECKIN, &prid);
		if (rc || prid < 0) {
			rc = RC(rc, "%s", "fsl_sym_to_rid");
			goto end;
		}
	}
	if (!artifact2 && diff_type != FNC_DIFF_BLOB) {
		diff_type = FNC_DIFF_CKOUT;
		fsl_ckout_version_info(f, &rid, NULL);
		if ((rc = fsl_ckout_changes_scan(f)))
			return RC(rc, "%s", "fsl_ckout_changes_scan");
		if (!fsl_strcmp(artifact1, "current") &&
		    !fsl_ckout_has_changes(f)) {
			fsl_fprintf(stdout, "No local changes.\n");
			return rc;
		}
	}
	while (fcli_next_arg(false) && diff_type != FNC_DIFF_BLOB) {
		struct fnc_pathlist_entry *ins;
		char *path, *path_to_diff;
		rc = map_repo_path(&path0);
		path = path0;
		while (path[0] == '/')
			++path;
		if (rc) {
			if (rc != FSL_RC_NOT_FOUND ||
			    (!fsl_strcmp(artifact1, "current") && !artifact2))
				goto end;
			rc = 0;
			fcli_err_reset();
			/* Path may be valid in tree of specified commit(s). */
			const fsl_card_F *cf = NULL;
			rc = fsl_deck_load_sym(f, &d, artifact1,
			    FSL_SATYPE_CHECKIN);
			if (rc)
				goto end;
			cf = fsl_deck_F_search(&d, path);
			if (cf == NULL) {
				if (!artifact2) {
					rc = RC(FSL_RC_NOT_FOUND,
					    "'%s' not found in tree [%s]", path,
					    artifact1);
					goto end;
				}
				fsl_deck_finalize(&d);
				rc = fsl_deck_load_sym(f, &d, artifact2,
				    FSL_SATYPE_CHECKIN);
				if (rc)
					goto end;
				cf = fsl_deck_F_search(&d, path);
				if (cf == NULL) {
					rc = RC(FSL_RC_NOT_FOUND,
					    "'%s' not found in trees [%s] [%s]",
					    path, artifact1, artifact2);
					goto end;
				}
			}
		}
		path_to_diff = fsl_strdup(path);
		if (path_to_diff == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		rc = fnc_pathlist_insert(&ins, &paths, path_to_diff, NULL);
		if (rc || ins == NULL /* Duplicate path. */)
			fsl_free(path_to_diff);
		if (rc)
			goto end;
	}

	if (diff_type != FNC_DIFF_BLOB && diff_type != FNC_DIFF_CKOUT) {
		q = fsl_stmt_malloc();
		rc = commit_builder(&commit, rid, q);
		if (rc)
			goto end;
		if (commit->prid == prid)
			showmeta = true;
		else {
			fsl_free(commit->puuid);
			commit->prid = prid;
			commit->puuid = fsl_rid_to_uuid(f, prid);
		}
	} else {
		commit = calloc(1, sizeof(*commit));
		if (commit == NULL) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
			    "%s", "calloc");
			goto end;
		}
		commit->prid = prid;
		commit->rid = rid;
		commit->puuid = fsl_rid_to_uuid(f, prid);
		commit->uuid = fsl_rid_to_uuid(f, rid);
		commit->type = fsl_strdup("blob");
		commit->diff_type = diff_type;
	}

	rc = init_curses();
	if (rc)
		goto end;

	if (fnc_init.context) {
		if ((rc = strtonumcheck(&context, fnc_init.context, INT_MIN,
		    INT_MAX)))
			goto end;
		context = MIN(DIFF_MAX_CTXT, context);
	}

	view = view_open(0, 0, 0, 0, FNC_VIEW_DIFF);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_diff_view(view, commit, context, fnc_init.ws,
	    fnc_init.invert, !fnc_init.quiet, NULL, showmeta, &paths);
	if (!rc)
		rc = view_loop(view);
end:
	fsl_free(path0);
	fsl_deck_finalize(&d);
	fsl_stmt_finalize(q);
	if (commit)
		fnc_commit_artifact_close(commit);
	TAILQ_FOREACH(pe, &paths, entry)
		free((char *)pe->path);
	fnc_pathlist_free(&paths);
	return rc;
}

static int
browse_commit_tree(struct fnc_view **new_view, int start_col,
    struct commit_entry *entry, const char *path)
{
	struct fnc_view	*tree_view;
	int		 rc = 0;

	tree_view = view_open(0, 0, 0, start_col, FNC_VIEW_TREE);
	if (tree_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_tree_view(tree_view, path, entry->commit->rid);
	if (rc)
		return rc;

	*new_view = tree_view;

	return rc;
}

static int
cmd_tree(fcli_command const *argv)
{
	fsl_cx		*f = fcli_cx();
	struct fnc_view	*view;
	char		*path = NULL;
	fsl_id_t	 rid;
	int		 rc = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		goto end;

	rc = map_repo_path(&path);
	if (rc)
		goto end;
	if (fnc_init.sym)
		rc = fsl_sym_to_rid(f, fnc_init.sym, FSL_SATYPE_ANY, &rid);
	else
		fsl_ckout_version_info(f, &rid, NULL);

	if (rc) {
		switch (rc) {
		case FSL_RC_AMBIGUOUS:
			RC(rc, "prefix too ambiguous [%s]",
			    fnc_init.sym);
			goto end;
		case FSL_RC_NOT_A_REPO:
			RC(rc, "%s tree needs a local checkout",
			    fcli_progname());
			goto end;
		case FSL_RC_NOT_FOUND:
			RC(rc, "invalid symbolic checkin name [%s]",
			    fnc_init.sym);
			goto end;
		case FSL_RC_MISUSE:
			/* FALL THROUGH */
		default:
			goto end;
		}
	}

	/* In 'fnc tree -R repo.db [path]' case, use the latest checkin. */
	if (rid == 0) {
		rc = fsl_sym_to_rid(f, "tip", FSL_SATYPE_CHECKIN, &rid);
		if (rc)
			goto end;
	} else if (!fsl_rid_is_a_checkin(f, rid)) {
		rc = RC(FSL_RC_TYPE, "%s tree requires check-in artifact",
		    fcli_progname());
		goto end;
	}

	rc = init_curses();
	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_TREE);
	if (view == NULL) {
		RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_tree_view(view, path, rid);
	if (!rc)
		rc = view_loop(view);
end:
	fsl_free(path);
	return rc;
}

static int
open_tree_view(struct fnc_view *view, const char *path, fsl_id_t rid)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_tree_view_state	*s = &view->state.tree;
	int				 rc = 0;

	TAILQ_INIT(&s->parents);
	s->show_id = false;
	s->colour = !fnc_init.nocolour && has_colors();
	s->rid = rid;
	s->commit_id = fsl_rid_to_uuid(f, rid);
	if (s->commit_id == NULL)
		return RC(FSL_RC_AMBIGUOUS, "%s", "fsl_rid_to_uuid");

	/*
	 * Construct tree of entire repository from which all (sub)tress will
	 * be derived. This object will be released when this view closes.
	 */
	rc = create_repository_tree(&s->repo, &s->commit_id, s->rid);
	if (rc)
		goto end;

	/*
	 * Open the initial root level of the repository tree now. Subtrees
	 * opened during traversal are built and destroyed on demand.
	 */
	rc = tree_builder(s->repo, &s->root, "/");
	if (rc)
		goto end;
	s->tree = s->root;
	/*
	 * If user has supplied a path arg (i.e., fnc tree path/in/repo), or
	 * has selected a commit from an 'fnc timeline path/in/repo' command,
	 * walk the path and open corresponding (sub)tree objects now.
	 */
	if (!fnc_path_is_root_dir(path)) {
		rc = walk_tree_path(s, s->repo, &s->root, path);
		if (rc)
			goto end;
	}


	if ((s->tree_label = fsl_mprintf("checkin %s", s->commit_id)) == NULL) {
		rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		goto end;
	}

	s->first_entry_onscreen = &s->tree->entries[0];
	s->selected_entry = &s->tree->entries[0];

	if (s->colour)
		set_colours(&s->colours, FNC_VIEW_TREE);

	view->show = show_tree_view;
	view->input = tree_input_handler;
	view->close = close_tree_view;
	view->search_init = tree_search_init;
	view->search_next = tree_search_next;
end:
	if (rc)
		close_tree_view(view);
	return rc;
}

/*
 * Decompose the supplied path into its constituent components, then build,
 * open and visit each subtree segment on the way to the requested entry.
 */
static int
walk_tree_path(struct fnc_tree_view_state *s, struct fnc_repository_tree *repo,
    struct fnc_tree_object **root, const char *path)
{
	struct fnc_tree_object	*tree = NULL;
	const char		*p;
	char			*slash, *subpath = NULL;
	int			 rc = 0;

	/* Find each slash and open preceding directory segment as a tree. */
	p = path;
	while (*p) {
		struct fnc_tree_entry	*te;
		char			*te_name;

		while (p[0] == '/')
			p++;

		slash = strchr(p, '/');
		if (slash == NULL)
			te_name = fsl_strdup(p);
		else
			te_name = fsl_strndup(p, slash - p);
		if (te_name == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			break;
		}

		te = find_tree_entry(s->tree, te_name, fsl_strlen(te_name));
		if (te == NULL) {
			rc = RC(FSL_RC_NOT_FOUND, "find_tree_entry(%s)",
			    te_name);
			fsl_free(te_name);
			break;
		}
		fsl_free(te_name);

		s->first_entry_onscreen = s->selected_entry = te;
		if (!S_ISDIR(s->selected_entry->mode))
			break;	/* If a file, jump to this entry. */

		slash = strchr(p, '/');
		if (slash)
			subpath = fsl_strndup(path, slash - path);
		else
			subpath = fsl_strdup(path);
		if (subpath == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			break;
		}

		rc = tree_builder(repo, &tree, subpath + 1 /* Leading slash */);
		if (rc)
			break;
		rc = visit_subtree(s, tree);
		if (rc) {
			fnc_object_tree_close(tree);
			break;
		}

		if (slash == NULL)
			break;
		fsl_free(subpath);
		subpath = NULL;
		p = slash;
	}

	fsl_free(subpath);
	return rc;
}

/*
 * This routine constructs the repository tree, repo, which is a DLL; from this
 * tree, all displayed (sub)trees are derived. File paths are extracted from F
 * cards of the checkin identified by id referenced in the repo database by rid.
 */
static int
create_repository_tree(struct fnc_repository_tree **repo, fsl_uuid_str *id,
    fsl_id_t rid)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_repository_tree	*ptr;
	fsl_deck			 d = fsl_deck_empty;
	const fsl_card_F		*cf = NULL;
	int				 rc = 0;

	ptr = fsl_malloc(sizeof(struct fnc_repository_tree));
	if (ptr == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	memset(ptr, 0, sizeof(struct fnc_repository_tree));

	rc = fsl_deck_load_rid(fcli_cx(), &d, rid, FSL_SATYPE_CHECKIN);
	if (rc)
		return RC(rc, "fsl_deck_load_rid(%d) [%s]", rid, id);
	rc = fsl_deck_F_rewind(&d);
	if (rc)
		goto end;;
	rc = fsl_deck_F_next(&d, &cf);
	if (rc)
		goto end;;

	while (cf) {
		char		*filename = NULL, *uuid = NULL;
		fsl_time_t	 mtime;

		filename = fsl_strdup(cf->name);
		if (filename == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		uuid = fsl_strdup(cf->uuid);
		if (uuid == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		rc = fsl_mtime_of_F_card(f, rid, cf, &mtime);
		if (!rc)
			rc = link_tree_node(ptr, filename, uuid, mtime);
		fsl_free(filename);
		fsl_free(uuid);
		if (!rc)
			rc = fsl_deck_F_next(&d, &cf);
		if (rc)
			goto end;
	}
end:
	fsl_deck_finalize(&d);

	*repo = ptr;
	return rc;
}

/*
 * This routine constructs the (sub)trees that are displayed. The directory dir
 * and its contents form a subtree, which is an array of tree entries copied
 * from DLL nodes in repo and stored in tree. This routine is called for each
 * directory that is displayed as a tree.
 */
static int
tree_builder(struct fnc_repository_tree *repo, struct fnc_tree_object **tree,
    const char *dir)
{
	struct fnc_tree_entry		*te = NULL;
	struct fnc_repo_tree_node	*tn = NULL;
	int				 i = 0;

	*tree = NULL;
	*tree = fsl_malloc(sizeof(**tree));
	if (*tree == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	memset(*tree, 0, sizeof(**tree));

	/* Count how many elements will comprise the tree to be allocated. */
	for(tn = repo->head; tn; tn = tn->next) {
		if ((!tn->parent_dir && fsl_strcmp(dir, "/")) ||
		    (tn->parent_dir && fsl_strcmp(dir, tn->parent_dir->path)))
			continue;
		++i;
	}
	(*tree)->entries = calloc(i, sizeof(struct fnc_tree_entry));
	if ((*tree)->entries == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
	/* Construct the tree to be displayed. */
	for(tn = repo->head, i = 0; tn; tn = tn->next) {
		if ((!tn->parent_dir && fsl_strcmp(dir, "/")) ||
		    (tn->parent_dir && fsl_strcmp(dir, tn->parent_dir->path)))
			continue;
		te = &(*tree)->entries[i];
		te->mode = tn->mode;
		te->mtime = tn->mtime;
		te->basename = fsl_strdup(tn->basename);
		if (te->basename == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->path = fsl_strdup(tn->path);
		if (te->path == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->uuid = fsl_strdup(tn->uuid);
		if (te->uuid == NULL && !S_ISDIR(te->mode))
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->idx = i++;
	}
	(*tree)->nentries = i;

	return 0;
}

#if 0
static void
delete_tree_node(struct fnc_tree_entry **head, struct fnc_tree_entry *del)
{
	struct fnc_tree_entry *temp = *head, *prev;

	if (temp == del) {
		*head = temp->next;
		fsl_free(temp);
		return;
	}

	while (temp != NULL && temp != del) {
		prev = temp;
		temp = temp->next;
	}

	if (temp == NULL)
		return;

	prev->next = temp->next;

	fsl_free(temp);
}
#endif

/*
 * This routine inserts nodes into the doubly-linked repository tree. Each
 * path component of path (i.e., tokens delimited by '/') becomes a node in
 * tree. The final path component of each segment is the node's .basename, and
 * its full repository relative path its .path. All files in a given directory
 * will comprise the directory node's .children list, and each file node's
 * .sibling list; said directory will be each file node's .parent_dir. The
 * elements of each requested tree will be identified by the node's .parent_dir;
 * that is, each node with the same parent_dir will be an entry in the same tree
 *   tree    The repository tree into which nodes are inserted
 *   path    The repository relative pathname of the versioned file
 *   uuid    The SHA hash of the file
 *   mtime   Modification time of the file
 * Returns 0 on success, non-zero on error.
 */
static int
link_tree_node(struct fnc_repository_tree *tree, const char *path,
    const char *uuid, fsl_time_t mtime)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_repo_tree_node	*parent_dir;
	fsl_buffer			 buf = fsl_buffer_empty;
	struct stat			 s;
	int				 i, rc = 0;

	parent_dir = tree->tail;
	while (parent_dir != 0 &&
	    (strncmp(parent_dir->path, path, parent_dir->pathlen) != 0 ||
            path[parent_dir->pathlen] != '/'))
		parent_dir = parent_dir->parent_dir;

	i = parent_dir ? parent_dir->pathlen + 1 : 0;

	while (path[i]) {
		struct fnc_repo_tree_node	*tn;
		int				 nodesz, slash = i;

		/* Find slash to demarcate each path component. */
		while (path[i] && path[i] != '/')
			i++;
		nodesz = sizeof(*tn) + i + 1;

		/*
		 * If not at end of path string, node is a directory so don't
		 * allocate space for the hash.
		 */
		if (uuid != 0 && path[i] == '\0')
			nodesz += FSL_STRLEN_K256 + 1; /* NUL */
		tn = fsl_malloc(nodesz);
		if (tn == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
		memset(tn, 0, sizeof(*tn));

		tn->path = (char *)&tn[1];
		memcpy(tn->path, path, i);
		tn->path[i] = '\0';
		tn->pathlen = i;

		if (uuid != 0 && path[i] == '\0') {
			tn->uuid = tn->path + i + 1;
			memcpy(tn->uuid, uuid, fsl_strlen(uuid) + 1);
		}

		tn->basename = tn->path + slash;

		/* Insert node into DLL or make it the head if first. */
		if (tree->tail) {
			tree->tail->next = tn;
			tn->prev = tree->tail;
		} else
			tree->head = tn;

		tree->tail = tn;
		tn->parent_dir = parent_dir;
		if (parent_dir) {
			if (parent_dir->children)
				parent_dir->lastchild->sibling = tn;
			else
				parent_dir->children = tn;
			tn->nparents = parent_dir->nparents + 1;
			parent_dir->lastchild = tn;
		} else {
			if (tree->rootail)
				tree->rootail->sibling = tn;
			tree->rootail = tn;
		}

		tn->mtime = mtime;
		while (path[i] == '/')	/* Consume slashes. */
			++i;
		parent_dir = tn;

		/* Stat path for tree display features. */
		rc = fsl_file_canonical_name2(f->ckout.dir, tn->path, &buf,
		    false);
		if (rc)
			goto end;
		if (lstat(fsl_buffer_cstr(&buf), &s) == -1) {
			if (errno == ENOENT)
				tn->mode = (!fsl_strcmp(tn->path, path) &&
				    tn->uuid) ? S_IFREG : S_IFDIR;
			else {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
				    "lstat(%s)", fsl_buffer_cstr(&buf));
				goto end;
			}
		} else
			tn->mode = s.st_mode;
		fsl_buffer_reuse(&buf);
	}

	while (parent_dir && parent_dir->parent_dir) {
		if (parent_dir->parent_dir->mtime < parent_dir->mtime)
			parent_dir->parent_dir->mtime = parent_dir->mtime;
		parent_dir = parent_dir->parent_dir;
	}
end:
	fsl_buffer_clear(&buf);
	return rc;
}

static int
show_tree_view(struct fnc_view *view)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	char				*treepath;
	int				 rc = 0;

	rc = tree_entry_path(&treepath, &s->parents, NULL);
	if (rc)
		return rc;

	rc = draw_tree(view, treepath);
	fsl_free(treepath);
	draw_vborder(view);

	return rc;
}

/*
 * Construct absolute repository path of the currently selected tree entry to
 * display in the tree view header, or pass to open_timeline_view() to construct
 * a timeline of all commits modifying path.
 */
static int
tree_entry_path(char **path, struct fnc_parent_trees *parents,
    struct fnc_tree_entry *te)
{
	struct fnc_parent_tree	*pt;
	size_t			 len = 2;  /* Leading slash and NUL. */
	int			 rc = 0;

	TAILQ_FOREACH(pt, parents, entry)
		len += strlen(pt->selected_entry->basename) + 1 /* slash */;
	if (te)
		len += strlen(te->basename);

	*path = calloc(1, len);
	if (path == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	(*path)[0] = '/';  /* Make it absolute from the repository root. */
	pt = TAILQ_LAST(parents, fnc_parent_trees);
	while (pt) {
		const char *name = pt->selected_entry->basename;
		if (strlcat(*path, name, len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, %s, %d)",
			    *path, name, len);
			goto end;
		}
		if (strlcat(*path, "/", len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, \"/\", %d)",
			    *path, len);
			goto end;
		}
		pt = TAILQ_PREV(pt, fnc_parent_trees, entry);
	}
	if (te) {
		if (strlcat(*path, te->basename, len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, %s, %d)",
			    *path, te->basename, len);
			goto end;
		}
	}
end:
	if (rc) {
		fsl_free(*path);
		*path = NULL;
	}
	return rc;
}

/*
 * Draw the currently visited tree. Headline view with the checkin's SHA hash,
 * and write subheader comprised of the tree path. Lexicographically order nodes
 * (cf. ls(1)) and postfix with identifier corresponding to the file mode as
 * returned by lstat(2) such that the tree takes the following form:
 *
 *  checkin COMMIT-HASH
 *  /absolute/repository/tree/path/
 *
 *   ..
 *   dir/
 *   executable*
 *   regularfile
 *   symlink@ -> /path/to/source/file
 *
 * If the 'i' key binding is entered, prefix each versioned file with its
 * SHA{1,3} hash. Directories, however, have no such hash UUID to display.
 */
static int
draw_tree(struct fnc_view *view, const char *treepath)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fnc_tree_entry		*te;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	int				 match = -1, rc = 0;
	int				 wstrlen, n, idx, nentries;
	int				 limit = view->nlines;
	uint_fast8_t			 hashlen = FSL_UUID_STRLEN_MIN;

	s->ndisplayed = 0;
	werase(view->window);
	if (limit == 0)
		return rc;

	/* Write (highlighted) headline (if view is active in splitscreen). */
	rc = formatln(&wcstr, &wstrlen, s->tree_label, view->ncols, 0);
	if (rc)
		return rc;
	if (screen_is_shared(view))
		wstandout(view->window);
	if (s->colour)
		c = get_colour(&s->colours, FNC_COMMIT_ID);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, wcstr);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	if (screen_is_shared(view))
		wstandend(view->window);
	fsl_free(wcstr);
	wcstr = NULL;
	if (wstrlen < view->ncols - 1)
		waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;

	/* Write this (sub)tree's absolute repository path subheader. */
	rc = formatln(&wcstr, &wstrlen, treepath, view->ncols, 0);
	if (rc)
		return rc;
	waddwstr(view->window, wcstr);
	fsl_free(wcstr);
	wcstr = NULL;
	if (wstrlen < view->ncols - 1)
		waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;
	waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;

	/* Write parent dir entry (i.e., "..") if top of the tree is in view. */
	if (s->first_entry_onscreen == NULL) {
		te = &s->tree->entries[0];
		if (s->selected_idx == 0) {
			if (view->active)
				wattr_on(view->window, A_REVERSE, NULL);
			s->selected_entry = NULL;
		}
		waddstr(view->window, "  ..\n");
		if (s->selected_idx == 0 && view->active)
			wattr_off(view->window, A_REVERSE, NULL);
		++s->ndisplayed;
		if (--limit <= 0)
			return rc;
		n = 1;
	} else {
		n = 0;
		te = s->first_entry_onscreen;
	}

	nentries = s->tree->nentries;
	for (idx = 0; idx < nentries; ++idx)	/* Find max hash length. */
		if (hashlen < fsl_strlen(s->tree->entries[idx].uuid))
			hashlen = fsl_strlen(s->tree->entries[idx].uuid);
	/* Iterate and write tree nodes postfixed with path type identifier. */
	for (idx = te->idx; idx < nentries; ++idx) {
		char		*line = NULL, *idstr = NULL, *targetlnk = NULL;
		const char	*modestr = "";
		mode_t		 mode;

		if (idx < 0 || idx >= s->tree->nentries)
			return 0;
		te = &s->tree->entries[idx];
		mode = te->mode;

		if (s->show_id) {
			idstr = fsl_strdup(te->uuid);
			/* Directories don't have UUIDs; pad with "..." dots. */
			if (idstr == NULL && !S_ISDIR(mode))
				return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			/* If needed, pad SHA1 hash to align w/ SHA3 hashes. */
			if (idstr == NULL || fsl_strlen(idstr) < hashlen) {
				char buf[hashlen], pad = '.';
				idstr = fsl_mprintf("%s%s", idstr ? idstr : "",
				    (char *)memset(buf, pad,
				    hashlen - fsl_strlen(idstr)));
				if (idstr == NULL)
					return RC(FSL_RC_RANGE,
					    "%s", "fsl_mprintf");
				idstr[hashlen] = '\0';
				/* idstr = fsl_mprintf("%*c", hashlen, ' '); */
			}
		}
		if (S_ISLNK(mode)) {
			fsl_size_t	ch;

			rc = tree_entry_get_symlink_target(&targetlnk, te);
			if (rc) {
				fsl_free(idstr);
				return rc;
			}
			for (ch = 0; ch < fsl_strlen(targetlnk); ++ch) {
				if (!isprint((unsigned char)targetlnk[ch]))
					targetlnk[ch] = '?';
			}
			modestr = "@";
		}
		else if (S_ISDIR(mode))
			modestr = "/";
		else if (mode & S_IXUSR)
			modestr = "*";
		if ((line = fsl_mprintf("%s  %s%s%s%s", idstr ? idstr : "",
		    te->basename, modestr, targetlnk ? " -> ": "",
		    targetlnk ? targetlnk : "")) == NULL) {
			fsl_free(idstr);
			fsl_free(targetlnk);
			return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		}
		fsl_free(idstr);
		fsl_free(targetlnk);
		rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0);
		if (rc) {
			fsl_free(line);
			break;
		}
		if (n == s->selected_idx) {
			if (view->active)
				wattr_on(view->window, A_REVERSE, NULL);
			s->selected_entry = te;
		}
		if (s->colour && (match = fsl_list_index_of(&s->colours, line,
		    match_line)) != -1)
			c = s->colours.list[match];
		else
			c = NULL;
		if (c)
			wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
		waddwstr(view->window, wcstr);
		if (c)
			wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
		if (wstrlen < view->ncols - 1)
			waddch(view->window, '\n');
		if (n == s->selected_idx && view->active)
			wattr_off(view->window, A_REVERSE, NULL);
		fsl_free(line);
		fsl_free(wcstr);
		wcstr = NULL;
		++n;
		++s->ndisplayed;
		s->last_entry_onscreen = te;
		if (--limit <= 0)
			break;
	}

	return rc;
}

static int
tree_entry_get_symlink_target(char **targetlnk, struct fnc_tree_entry *te)
{
	struct stat	 s;
	fsl_buffer	 fb = fsl_buffer_empty;
	char		*buf = NULL;
	ssize_t		 nbytes, bufsz;
	int		 rc = 0;

	*targetlnk = NULL;

	fsl_file_canonical_name2(fcli_cx()->ckout.dir, te->path, &fb, false);
	if (lstat(fsl_buffer_cstr(&fb), &s) == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), "lstat(%s)",
		    fsl_buffer_cstr(&fb));
		goto end;
	}

	bufsz = s.st_size ? (s.st_size + 1 /* NUL */) : PATH_MAX;
	buf = fsl_malloc(bufsz);
	if (buf == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_malloc");
		goto end;
	}

	nbytes = readlink(fsl_buffer_cstr(&fb), buf, bufsz);
	if (nbytes == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "readlink(%s)",
		    fsl_buffer_cstr(&fb));
		goto end;
	}
	buf[nbytes] = '\0';	/* readlink() does _not_ NUL terminate */
end:
	fsl_buffer_clear(&fb);
	if (rc)
		fsl_free(buf);
	*targetlnk = buf;
	return rc;
	/*
	 * XXX Not sure if we should rely on fossil(1) populating symlinks
	 * with the path of the target source file to obtain the target link.
	 */
	/* fsl_cx		*f = fcli_cx(); */
	/* fsl_buffer	 blob = fsl_buffer_empty; */
	/* fsl_id_t	 rid; */

	/* if (!((te->mode & (S_IFDIR | S_IFLNK)) == S_IFLNK)) */
	/* 	return RC(FSL_RC_TYPE, "file not symlink [%s]", te->path); */
	/* rc = fsl_sym_to_rid(f, te->uuid, FSL_SATYPE_ANY, &rid); */
	/* if (!rc) */
	/* 	rc = fsl_content_blob(f, rid, &blob); */
	/* if (rc) */
	/* 	return rc; */

	/* *targetlnk = fsl_strdup(fsl_buffer_str(&blob)); */
	/* fsl_buffer_clear(&blob); */
}

static int
tree_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_view			*timeline_view/*, *branch_view */;
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fnc_tree_entry		*te;
	int				 n, start_col = 0, rc = 0;

	switch (ch) {
	case 'c':
		s->colour = !s->colour;
		break;
	case 'i':
		s->show_id = !s->show_id;
		break;
	case 't':
		if (!s->selected_entry)
			break;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		rc = timeline_tree_entry(&timeline_view, start_col, s);
		view->active = false;
		timeline_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				return rc;
			view_set_child(view, timeline_view);
			view->focus_child = true;
		} else
			*new_view = timeline_view;
		break;
	case 'g':
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	case KEY_HOME:
		s->selected_idx = 0;
		if (s->tree == s->root)
			s->first_entry_onscreen = &s->tree->entries[0];
		else
			s->first_entry_onscreen = NULL;
		break;
	case KEY_END:
	case 'G':
		s->selected_idx = 0;
		te = &s->tree->entries[s->tree->nentries - 1];
		for (n = 0; n < view->nlines - 3; ++n) {
			if (te == NULL) {
				if(s->tree != s->root) {
					s->first_entry_onscreen = NULL;
					++n;
				}
				break;
			}
			s->first_entry_onscreen = te;
			te = get_tree_entry(s->tree, te->idx - 1);
		}
		if (n > 0)
			s->selected_idx = n - 1;
		break;
	case KEY_UP:
	case 'k':
		if (s->selected_idx > 0) {
			--s->selected_idx;
			break;
		}
		tree_scroll_up(s, 1);
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->tree == s->root) {
			if (&s->tree->entries[0] == s->first_entry_onscreen)
				s->selected_idx = 0;
		} else {
			if (s->first_entry_onscreen == NULL)
				s->selected_idx = 0;
		}
		tree_scroll_up(s, MAX(0, view->nlines - 3));
		break;
	case KEY_DOWN:
	case 'j':
		if (s->selected_idx < s->ndisplayed - 1) {
			++s->selected_idx;
			break;
		}
		if (get_tree_entry(s->tree, s->last_entry_onscreen->idx + 1)
		    == NULL)
			break;	/* Reached last entry. */
		tree_scroll_down(s, 1);
		break;
	case KEY_NPAGE:
	case CTRL('f'):
		if (get_tree_entry(s->tree, s->last_entry_onscreen->idx + 1)
		    == NULL) {
			/*
			 * When the last entry on screen is the last node in the
			 * tree move cursor to it instead of scrolling the view.
			 */
			if (s->selected_idx < s->ndisplayed - 1)
				s->selected_idx = s->ndisplayed - 1;
			break;
		}
		tree_scroll_down(s, view->nlines - 3);
		break;
	case KEY_BACKSPACE:
	case KEY_ENTER:
	case KEY_LEFT:
	case KEY_RIGHT:
	case '\r':
	case 'h':
	case 'l':
		/*
		 * h/backspace/arrow-left: return to parent dir irrespective
		 * of selected entry type (unless already at root).
		 * l/arrow-right: move into selected dir entry.
		 */
		if (ch != KEY_RIGHT && ch != 'l' && (s->selected_entry == NULL
		    || ch == 'h' || ch == KEY_BACKSPACE || ch == KEY_LEFT)) {
			struct fnc_parent_tree	*parent;
			/* h/backspace/left-arrow pressed or ".." selected. */
			if (s->tree == s->root)
				break;
			parent = TAILQ_FIRST(&s->parents);
			TAILQ_REMOVE(&s->parents, parent,
			    entry);
			fnc_object_tree_close(s->tree);
			s->tree = parent->tree;
			s->first_entry_onscreen = parent->first_entry_onscreen;
			s->selected_entry = parent->selected_entry;
			s->selected_idx = parent->selected_idx;
			fsl_free(parent);
		} else if (s->selected_entry != NULL &&
		    S_ISDIR(s->selected_entry->mode)) {
			struct fnc_tree_object	*subtree = NULL;
			rc = tree_builder(s->repo, &subtree,
			    s->selected_entry->path);
			if (rc)
				break;
			rc = visit_subtree(s, subtree);
			if (rc) {
				fnc_object_tree_close(subtree);
				break;
			}
		} else if (S_ISREG(s->selected_entry->mode)) {
			struct fnc_view *blame_view;
			int start_col = view_is_parent(view) ?
			    view_split_start_col(view->start_col) : 0;

			rc = blame_tree_entry(&blame_view, start_col,
			    s->selected_entry, &s->parents, s->commit_id);
			if (rc)
				break;
			view->active = false;
			blame_view->active = true;
			if (view_is_parent(view)) {
				rc = view_close_child(view);
				if (rc)
					return rc;
				view_set_child(view, blame_view);
				view->focus_child = true;
			} else
				*new_view = blame_view;
		}
		break;
	case KEY_RESIZE:
		if (view->nlines >= 4 && s->selected_idx >= view->nlines - 3)
			s->selected_idx = view->nlines - 4;
		break;
	default:
		break;
	}

	return rc;
}

static int
timeline_tree_entry(struct fnc_view **new_view, int start_col,
    struct fnc_tree_view_state *s)
{
	struct fnc_view	*timeline_view;
	char		*path;
	int		 rc = 0;

	*new_view = NULL;

	timeline_view = view_open(0, 0, 0, start_col, FNC_VIEW_TIMELINE);
	if (timeline_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	/* Construct repository relative path for timeline query. */
	rc = tree_entry_path(&path, &s->parents, s->selected_entry);
	if (rc)
		return rc;

	rc = open_timeline_view(timeline_view, s->rid, path);
	if (rc)
		view_close(timeline_view);
	else
		*new_view = timeline_view;

	fsl_free(path);
	return rc;
}

static void
tree_scroll_up(struct fnc_tree_view_state *s, int maxscroll)
{
	struct fnc_tree_entry	*te;
	int			 isroot, i = 0;

	isroot = s->tree == s->root;

	if (s->first_entry_onscreen == NULL)
		return;

	te = get_tree_entry(s->tree, s->first_entry_onscreen->idx - 1);
	while (i++ < maxscroll) {
		if (te == NULL) {
			if (!isroot)
				s->first_entry_onscreen = NULL;
			break;
		}
		s->first_entry_onscreen = te;
		te = get_tree_entry(s->tree, te->idx - 1);
	}
}

static void
tree_scroll_down(struct fnc_tree_view_state *s, int maxscroll)
{
	struct fnc_tree_entry	*next, *last;
	int			 n = 0;

	if (s->first_entry_onscreen)
		next = get_tree_entry(s->tree,
		    s->first_entry_onscreen->idx + 1);
	else
		next = &s->tree->entries[0];

	last = s->last_entry_onscreen;
	while (next && last && n++ < maxscroll) {
		last = get_tree_entry(s->tree, last->idx + 1);
		if (last) {
			s->first_entry_onscreen = next;
			next = get_tree_entry(s->tree, next->idx + 1);
		}
	}
}

static int
visit_subtree(struct fnc_tree_view_state *s, struct fnc_tree_object *subtree)
{
	struct fnc_parent_tree	*parent;

	parent = calloc(1, sizeof(*parent));
	if (parent == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	parent->tree = s->tree;
	parent->first_entry_onscreen = s->first_entry_onscreen;
	parent->selected_entry = s->selected_entry;
	parent->selected_idx = s->selected_idx;
	TAILQ_INSERT_HEAD(&s->parents, parent, entry);
	s->tree = subtree;
	s->selected_idx = 0;
	s->first_entry_onscreen = NULL;

	return 0;
}

static int
blame_tree_entry(struct fnc_view **new_view, int start_col,
    struct fnc_tree_entry *te, struct fnc_parent_trees *parents,
    fsl_uuid_str commit_id)
{
	struct fnc_view	*blame_view;
	char		*path;
	int		 rc = 0;

	*new_view = NULL;

	rc = tree_entry_path(&path, parents, te);
	if (rc)
		return rc;

	blame_view = view_open(0, 0, 0, start_col, FNC_VIEW_BLAME);
	if (blame_view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_blame_view(blame_view, path, commit_id, 0, 0);
	if (rc)
		view_close(blame_view);
	else
		*new_view = blame_view;
end:
	fsl_free(path);
	return rc;
}

static int
tree_search_init(struct fnc_view *view)
{
	struct fnc_tree_view_state *s = &view->state.tree;

	s->matched_entry = NULL;
	return 0;
}

static int
tree_search_next(struct fnc_view *view)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fnc_tree_entry		*te = NULL;
	int				 rc = 0;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
		return rc;
	}

	if (s->matched_entry) {
		if (view->searching == SEARCH_FORWARD) {
			if (s->selected_entry)
				te = &s->tree->entries[s->selected_entry->idx
				    + 1];
			else
				te = &s->tree->entries[0];
		} else {
			if (s->selected_entry == NULL)
				te = &s->tree->entries[s->tree->nentries - 1];
			else
				te = &s->tree->entries[s->selected_entry->idx
				    - 1];
		}
	} else {
		if (view->searching == SEARCH_FORWARD)
			te = &s->tree->entries[0];
		else
			te = &s->tree->entries[s->tree->nentries - 1];
	}

	while (1) {
		if (te == NULL) {
			if (s->matched_entry == NULL) {
				view->search_status = SEARCH_CONTINUE;
				return rc;
			}
			if (view->searching == SEARCH_FORWARD)
				te = &s->tree->entries[0];
			else
				te = &s->tree->entries[s->tree->nentries - 1];
		}

		if (match_tree_entry(te, &view->regex)) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_entry = te;
			break;
		}

		if (view->searching == SEARCH_FORWARD)
			te = &s->tree->entries[te->idx + 1];
		else
			te = &s->tree->entries[te->idx - 1];
	}

	if (s->matched_entry) {
		s->first_entry_onscreen = s->matched_entry;
		s->selected_idx = 0;
	}

	return rc;
}

static int
match_tree_entry(struct fnc_tree_entry *te, regex_t *regex)
{
	regmatch_t regmatch;

	return regexec(regex, te->basename, 1, &regmatch, 0) == 0;
}

struct fnc_tree_entry *
get_tree_entry(struct fnc_tree_object *tree, int i)
{
	if (i < 0 || i >= tree->nentries)
		return NULL;

	return &tree->entries[i];
}

/* Find entry in tree with basename name. */
static struct fnc_tree_entry *
find_tree_entry(struct fnc_tree_object *tree, const char *name, size_t len)
{
	int	idx;

	/* Entries are sorted in strcmp() order. */
	for (idx = 0; idx < tree->nentries; ++idx) {
		struct fnc_tree_entry *te = &tree->entries[idx];
		int cmp = strncmp(te->basename, name, len);
		if (cmp < 0)
			continue;
		if (cmp > 0)
			break;
		if (te->basename[len] == '\0')
			return te;
	}
	return NULL;
}

static int
close_tree_view(struct fnc_view *view)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fsl_list_state		 st = { FNC_COLOUR_OBJ };

	fsl_list_clear(&s->colours, fsl_list_object_free, &st);

	fsl_free(s->tree_label);
	s->tree_label = NULL;
	fsl_free(s->commit_id);
	s->commit_id = NULL;

	while (!TAILQ_EMPTY(&s->parents)) {
		struct fnc_parent_tree *parent;
		parent = TAILQ_FIRST(&s->parents);
		TAILQ_REMOVE(&s->parents, parent, entry);
		if (parent->tree != s->root)
			fnc_object_tree_close(parent->tree);
		fsl_free(parent);

	}

	if (s->tree != NULL && s->tree != s->root)
		fnc_object_tree_close(s->tree);
	if (s->root)
		fnc_object_tree_close(s->root);
	if (s->repo)
		fnc_close_repository_tree(s->repo);

	return 0;
}

static void
fnc_object_tree_close(struct fnc_tree_object *tree)
{
	int	idx;

	for (idx = 0; idx < tree->nentries; ++idx) {
		fsl_free(tree->entries[idx].basename);
		fsl_free(tree->entries[idx].path);
		fsl_free(tree->entries[idx].uuid);
	}

	fsl_free(tree->entries);
	fsl_free(tree);
}

static void
fnc_close_repository_tree(struct fnc_repository_tree *repo)
{
	struct fnc_repo_tree_node *next, *tn;

	tn = repo->head;
	while (tn) {
		next = tn->next;
		fsl_free(tn);
		tn = next;
	}
	fsl_free(repo);
}

static int
view_close_child(struct fnc_view *view)
{
	int	rc = 0;

	if (view->child == NULL)
		return rc;

	rc = view_close(view->child);
	view->child = NULL;

	return rc;
}

static void
view_set_child(struct fnc_view *view, struct fnc_view *child)
{
	view->child = child;
	child->parent = view;
}

static int
set_colours(fsl_list *s, enum fnc_view_id vid)
{
	struct fnc_colour	 *colour;
	const char		**regexp = NULL;
	const char		 *regexp_blame[] = {"^"};
	const char		 *regexp_timeline[] = {"^$", "^$", "^$"};
	const char		 *regexp_tree[] = {"@$", "/$", "\\*$", "^$"};
	const char		 *regexp_diff[] = {
				    "^((checkin|wiki|ticket|technote) "
				    "[0-9a-f]|hash [+-] |\\[[+~>-]] |"
				    "[+-]{3} )", "^user:", "^date:", "^tags:",
				    "^-", "^\\+", "^@@"
				  };
	int			  pairs_diff[][2] = {
				    {FNC_DIFF_META, COLOR_GREEN},
				    {FNC_USER_STR, COLOR_CYAN},
				    {FNC_DATE_STR, COLOR_YELLOW},
				    {FNC_TAGS_STR, COLOR_MAGENTA},
				    {FNC_DIFF_MINUS, COLOR_MAGENTA},
				    {FNC_DIFF_PLUS, COLOR_CYAN},
				    {FNC_DIFF_CHNK, COLOR_YELLOW}
				  };
	int			  pairs_tree[][2] = {
				    {FNC_TREE_LINK, COLOR_MAGENTA},
				    {FNC_TREE_DIR, COLOR_CYAN},
				    {FNC_TREE_EXEC, COLOR_GREEN},
				    {FNC_COMMIT_ID, COLOR_GREEN}
				  };
	int			  pairs_timeline[][2] = {
				    {FNC_COMMIT_ID, COLOR_GREEN},
				    {FNC_USER_STR, COLOR_CYAN},
				    {FNC_DATE_STR, COLOR_YELLOW}
				  };
	int			  pairs_blame[][2] = {
				    {FNC_COMMIT_ID, COLOR_GREEN}
				  };
	int			(*pairs)[2], rc = 0;
	fsl_size_t		  idx, n;

	switch (vid) {
	case FNC_VIEW_DIFF:
		n = nitems(regexp_diff);
		regexp = regexp_diff;
		pairs = pairs_diff;
		break;
	case FNC_VIEW_TREE:
		n = nitems(regexp_tree);
		regexp = regexp_tree;
		pairs = pairs_tree;
		break;
	case FNC_VIEW_TIMELINE:
		n = nitems(regexp_timeline);
		regexp = regexp_timeline;
		pairs = pairs_timeline;
		break;
	case FNC_VIEW_BLAME:
		n = nitems(regexp_blame);
		regexp = regexp_blame;
		pairs = pairs_blame;
		break;
	default:
		return RC(FSL_RC_TYPE, "%s", "invalid fnc_view_id");
	}

	for (idx = 0; idx < n; ++idx) {
		colour = fsl_malloc(sizeof(*colour));
		if (colour == NULL)
			return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
			    "%s", "fsl_malloc");

		rc = regcomp(&colour->regex, regexp[idx],
		    REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
		if (rc) {
			static char regerr[512];
			regerror(rc, &colour->regex, regerr, sizeof(regerr));
			fsl_free(colour);
			return RC(FSL_RC_ERROR, "regcomp(%s) -> %s",
			    regexp[idx], regerr);
		}

		colour->scheme = pairs[idx][0];
		init_pair(colour->scheme, pairs[idx][1], -1);
		fsl_list_append(s, colour);
	}

	return rc;
}

struct fnc_colour *
get_colour(fsl_list *colours, int scheme)
{
	struct fnc_colour	cs;
	int			match = -1;

	cs.scheme = scheme;
	match = fsl_list_index_of(colours, &cs, match_colour);

	if (match != -1)
		return colours->list[match];

	return NULL;
}

static int
match_colour(const void *target, const void *key)
{
	struct fnc_colour *c = (struct fnc_colour *)key;
	struct fnc_colour *t = (struct fnc_colour *)target;

	return (c->scheme == t->scheme) ? 0 : 1;
}

/*
 * Emulate vim(1) gg: User has 1 sec to follow first 'g' keypress with another.
 */
static bool
fnc_home(struct fnc_view *view)
{
	bool	home = true;

	halfdelay(10);	/* Block for 1 second, then return ERR. */
	if (wgetch(view->window) != 'g')
		home = false;
	cbreak();	/* Return to blocking mode on user input. */

	return home;
}

static int
cmd_blame(fcli_command const *argv)
{
	fsl_cx		*f = fcli_cx();
	struct fnc_view	*view;
	char		*path = NULL;
	fsl_uuid_str	 commit_id = NULL;
	fsl_id_t	 tip = 0, rid = 0;
	int		 nlimit = 0, rc = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		goto end;
	if (!fcli_next_arg(false)) {
		rc = RC(FSL_RC_MISSING_INFO,
		    "%s blame requires versioned file path", fcli_progname());
		goto end;
	}

	if (fnc_init.nrecords.zlimit) {
		char *n = (char *)fnc_init.nrecords.zlimit;
		bool timed;
		if (n[fsl_strlen(n) - 1] == 's') {
			n[fsl_strlen(n) - 1] = '\0';
			timed = true;
		}
		if ((rc = strtonumcheck(&nlimit, n, INT_MIN, INT_MAX)))
			goto end;
		if (timed)
			nlimit *= -1;
	}

	if (fnc_init.sym || fnc_init.reverse) {
		if (fnc_init.reverse) {
			if (!fnc_init.sym) {
				rc = RC(FSL_RC_MISSING_INFO,
				    "%s blame --reverse requires --commit",
				    fcli_progname());
				goto end;
			}
			rc = fsl_sym_to_rid(f, "tip", FSL_SATYPE_CHECKIN, &tip);
			if (rc)
				goto end;
		}
		rc = fsl_sym_to_rid(f, fnc_init.sym, FSL_SATYPE_CHECKIN, &rid);
		if (rc)
			goto end;
	} else if (!fnc_init.sym)
		fsl_ckout_version_info(f, &rid, NULL);

	rc = map_repo_path(&path);
	if (rc) {
		if (rc != FSL_RC_NOT_FOUND || !fnc_init.sym)
			goto end;
		/* Path may be valid in repository tree of specified commit. */
		rc = 0;
		fcli_err_reset();
	}

	commit_id = fsl_rid_to_uuid(f, rid);
	if (rc || (path[0] == '/' && path[1] == '\0')) {
		rc = rc ? rc : RC(FSL_RC_MISSING_INFO,
		    "%s blame requires versioned file path", fcli_progname());
		goto end;
	}

	init_curses();

	view = view_open(0, 0, 0, 0, FNC_VIEW_BLAME);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", view_open);
		goto end;
	}

	rc = open_blame_view(view, path, commit_id, tip, nlimit);
	if (rc)
		goto end;
	rc = view_loop(view);
end:
	fsl_free(path);
	fsl_free(commit_id);
	return rc;
}

static int
open_blame_view(struct fnc_view *view, char *path, fsl_uuid_str commit_id,
    fsl_id_t tip, int nlimit)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 rc = 0;

	CONCAT(STAILQ, _INIT)(&s->blamed_commits);

	s->path = fsl_strdup(path);
	if (s->path == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");

	rc = fnc_commit_qid_alloc(&s->blamed_commit, commit_id);
	if (rc) {
		fsl_free(s->path);
		return rc;
	}

	CONCAT(STAILQ, _INSERT_HEAD)(&s->blamed_commits, s->blamed_commit,
	    entry);
	memset(&s->blame, 0, sizeof(s->blame));
	s->first_line_onscreen = 1;
	s->last_line_onscreen = view->nlines;
	s->selected_line = 1;
	s->blame_complete = false;
	s->commit_id = commit_id;
	s->blame.origin = tip;
	s->blame.nlimit = nlimit;
	s->spin_idx = 0;
	s->colour = !fnc_init.nocolour && has_colors();

	if (s->colour) {
		rc = set_colours(&s->colours, FNC_VIEW_BLAME);
		if (rc)
			return rc;
	}

	view->show = show_blame_view;
	view->input = blame_input_handler;
	view->close = close_blame_view;
	view->search_init = blame_search_init;
	view->search_next = blame_search_next;

	return run_blame(view);
}

static int
run_blame(struct fnc_view *view)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_blame_view_state	*s = &view->state.blame;
	struct fnc_blame		*blame = &s->blame;
	fsl_deck			 d = fsl_deck_empty;
	fsl_buffer			 buf = fsl_buffer_empty;
	fsl_annotate_opt		*opt = NULL;
	const fsl_card_F		*cf;
	char				*filepath = NULL;
	char				*master = NULL, *root = NULL;
	int				 rc = 0;

	/*
	 * Trim prefixed '/' if path has been processed by map_repo_path(),
	 * which only occurs when the -c option has not been passed.
	 * XXX This slash trimming is cumbersome; we should not prefix a slash
	 * in map_repo_path() as we only want the slash for displaying an
	 * absolute-repository-relative path, so we should prefix it only then.
	 */
	filepath = s->path[0] != '/' ? s->path : s->path + 1;

	rc = fsl_deck_load_sym(f, &d, s->blamed_commit->id, FSL_SATYPE_CHECKIN);
	if (rc)
		goto end;

	cf = fsl_deck_F_search(&d, filepath);
	if (cf == NULL) {
		rc = RC(FSL_RC_NOT_FOUND, "'%s' not found in tree [%s]",
		    filepath, s->blamed_commit->id);
		goto end;
	}
	rc = fsl_card_F_content(f, cf, &buf);
	if (rc)
		goto end;

	/*
	 * We load f with the actual file content to map line offsets so we
	 * accurately find tokens when running a search.
	 */
	blame->f = tmpfile();
	if (blame->f == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "tmpfile");
		goto end;
	}

	opt = &blame->thread_cx.blame_opt;
	opt->filename = fsl_strdup(filepath);
	fcli_fax((char *)opt->filename);
	rc = fsl_sym_to_rid(f, s->blamed_commit->id, FSL_SATYPE_CHECKIN,
	    &opt->versionRid);
	if (rc)
		goto end;
	opt->originRid = blame->origin;    /* tip when -r is passed */
	if (blame->nlimit < 0)
		opt->limitMs = abs(blame->nlimit) * 1000;
	else
		opt->limitVersions = blame->nlimit;
	opt->out = blame_cb;
	opt->outState = &blame->cb_cx;

	rc = fnc_dump_buffer_to_file(&blame->filesz, &blame->nlines,
	    &blame->line_offsets, blame->f, &buf);
	if (rc)
		goto end;
	if (blame->nlines == 0) {
		s->blame_complete = true;
		goto end;
	}

	/* Don't include EOF \n in blame line count. */
	if (blame->line_offsets[blame->nlines - 1] == blame->filesz)
		--blame->nlines;

	blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
	if (blame->lines == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
		goto end;
	}

	master = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", NULL);
	if (master == NULL) {
		master = fsl_strdup("trunk");
		if (master == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	}
	root = fsl_mprintf("root:%s", master);
	rc = fsl_sym_to_uuid(f, root, FSL_SATYPE_CHECKIN,
	    &blame->cb_cx.root_commit, NULL);
	if (rc) {
		rc = RC(rc, "%s", "fsl_sym_to_uuid");
		goto end;
	}

	blame->cb_cx.view = view;
	blame->cb_cx.lines = blame->lines;
	blame->cb_cx.nlines = blame->nlines;
	blame->cb_cx.commit_id = fsl_strdup(s->blamed_commit->id);
	if (blame->cb_cx.commit_id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}
	blame->cb_cx.quit = &s->done;

	blame->thread_cx.path = s->path;
	blame->thread_cx.cb_cx = &blame->cb_cx;
	blame->thread_cx.complete = &s->blame_complete;
	blame->thread_cx.cancel_cb = cancel_blame;
	blame->thread_cx.cancel_cx = &s->done;
	s->blame_complete = false;

	if (s->first_line_onscreen + view->nlines - 1 > blame->nlines) {
		s->first_line_onscreen = 1;
		s->last_line_onscreen = view->nlines;
		s->selected_line = 1;
	}

end:
	fsl_free(master);
	fsl_free(root);
	fsl_deck_finalize(&d);
	fsl_buffer_clear(&buf);
	if (rc)
		stop_blame(blame);
	return rc;
}

/*
 * Write file content in buf to out file. Record the number of lines in the file
 * in nlines, and total bytes written in filesz. Assign byte offsets of each
 * line to the dynamically allocated *line_offsets, which must eventually be
 * disposed of by the caller. Flush and rewind out file when done.
 */
static int
fnc_dump_buffer_to_file(off_t *filesz, int *nlines, off_t **line_offsets,
    FILE *out, fsl_buffer *buf)
{
	off_t		 off = 0, total_len = 0;
	size_t		 len, n, i = 0, nalloc = 0;
	int		 rc = 0;
	const int	 alloc_chunksz = MIN(512, BUFSIZ);

	if (line_offsets)
		*line_offsets = NULL;
	if (filesz)
		*filesz = 0;
	if (nlines)
		*nlines = 0;

	len = buf->used;
	if (len == 0)
		return RC(FSL_RC_SIZE_MISMATCH, "%s",
		    "fnc_dump_buffer_to_file");
	if (nlines) {
		if (line_offsets && *line_offsets == NULL) {
			*nlines = 1;
			nalloc = alloc_chunksz;
			*line_offsets = calloc(nalloc, sizeof(**line_offsets));
			if (*line_offsets == NULL)
				return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
				    "%s", "calloc");

			/* Consume the first line. */
			while (i < len) {
				if (buf->mem[i] == '\n')
					break;
				++i;
			}
		}
		/* Scan '\n' offsets. */
		while (i < len) {
			if (buf->mem[i] != '\n') {
				++i;
				continue;
			}
			++(*nlines);
			if (line_offsets && nalloc < (size_t)*nlines) {
				size_t n, oldsz, newsz;
				off_t *new = NULL;

				n = *nlines + alloc_chunksz;
				oldsz = nalloc * sizeof(**line_offsets);
				newsz = n * sizeof(**line_offsets);
				if (newsz <= oldsz) {
					size_t b = oldsz - newsz;
					if (b < oldsz / 2 &&
					    b < (size_t)getpagesize()) {
						memset((char *)*line_offsets
						    + newsz, 0, b);
						goto allocated;
					}
				}
				new = fsl_realloc(*line_offsets, newsz);
				if (new == NULL) {
					fsl_free(*line_offsets);
					*line_offsets = NULL;
					return RC(FSL_RC_ERROR, "%s",
					    "fsl_realloc");
				}
				*line_offsets = new;
allocated:
				nalloc = n;
			}
			if (line_offsets) {
				off = total_len + i + 1;
				(*line_offsets)[*nlines - 1] = off;
			}
			++i;
		}
	}
	n = fwrite(buf->mem, 1, len, out);
	if (n != len)
		return RC(ferror(out) ? fsl_errno_to_rc(errno, FSL_RC_IO)
		    : FSL_RC_IO, "%s", "fwrite");
	total_len += len;

	if (fflush(out) != 0)
		return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fflush");
	rewind(out);

	if (filesz)
		*filesz = total_len;

	return rc;
}

static int
show_blame_view(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 rc = 0;

	if (!s->blame.thread_id && !s->blame_complete) {
		rc = pthread_create(&s->blame.thread_id, NULL, blame_thread,
		    &s->blame.thread_cx);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_create");

		halfdelay(1);	/* Fast refresh while annotating.  */
	}

	if (s->blame_complete)
		cbreak();	/* Return to blocking mode. */

	rc = draw_blame(view);
	draw_vborder(view);

	return rc;
}

static void *
blame_thread(void *state)
{
	struct fnc_blame_thread_cx	*cx = state;
	int				 rc0, rc;

	rc = block_main_thread_signals();
	if (rc)
		return (void *)(intptr_t)rc;

	rc = fsl_annotate(fcli_cx(), &cx->blame_opt);
	if (rc && fsl_cx_err_get_e(fcli_cx())->code == FSL_RC_BREAK) {
		fcli_err_reset();
		rc = 0;
	}

	rc0 = pthread_mutex_lock(&fnc_mutex);
	if (rc0)
		return (void *)(intptr_t)RC(fsl_errno_to_rc(rc0, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	*cx->complete = true;

	rc0 = pthread_mutex_unlock(&fnc_mutex);
	if (rc0 && !rc)
		rc = RC(fsl_errno_to_rc(rc0, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");

	return (void *)(intptr_t)rc;
}

static int
blame_cb(void *state, fsl_annotate_opt const * const opt,
    fsl_annotate_step const * const step)
{
	struct fnc_blame_cb_cx	*cx = state;
	struct fnc_blame_line	*line;
	int			 rc = 0;

	rc = pthread_mutex_lock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	if (*cx->quit) {
		rc = fcli_err_set(FSL_RC_BREAK, "user quit");
		goto end;
	}

	line = &cx->lines[step->lineNumber - 1];
	if (line->annotated)
		goto end;

	if (step->mtime) {
		line->id = fsl_strdup(step->versionHash);
		if (line->id == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", fsl_strdup);
			goto end;
		}
		line->annotated = true;
	} else
		line->id = NULL;

	/* -r can return lines with no version, so use root check-in. */
	if (opt->originRid && !line->id) {
		line->id = fsl_strdup(cx->root_commit);
		line->annotated = true;
	}

	++cx->nlines;
end:
	rc = pthread_mutex_unlock(&fnc_mutex);
	if (rc)
		rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");
	return rc;
}

static int
draw_blame(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	struct fnc_blame		*blame = &s->blame;
	struct fnc_blame_line		*blame_line;
	regmatch_t			*regmatch = &view->regmatch;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	char				*line = NULL;
	fsl_uuid_str			 prev_id = NULL, id_str = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 width, lineno = 0, nprinted = 0;
	int				 rc = 0;
	const int			 idfield = 11;  /* Prefix + space. */

	id_str = fsl_strdup(s->blamed_commit->id);
	if (id_str == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");

	rewind(blame->f);
	werase(view->window);

	if ((line = fsl_mprintf("checkin %s", id_str)) == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "fsl_mprintf");
		fsl_free(id_str);
		return rc;
	}

	rc = formatln(&wcstr, &width, line, view->ncols, 0);
	fsl_free(line);
	line = NULL;
	if (rc)
		return rc;
	if (screen_is_shared(view))
		wstandout(view->window);
	if (s->colour)
		c = get_colour(&s->colours, FNC_COMMIT_ID);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, wcstr);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	if (screen_is_shared(view))
		wstandend(view->window);
	fsl_free(wcstr);
	wcstr = NULL;
	if (width < view->ncols - 1)
		waddch(view->window, '\n');

	line = fsl_mprintf("[%d/%d] %s%s%s %c",
	    s->first_line_onscreen - 1 + s->selected_line, blame->nlines,
	    s->blame_complete ? "" : "annotating... ",
	    fnc_init.sym ? "/" : "", s->path,
	    s->blame_complete ? ' ' : SPINNER[s->spin_idx]);
	if (SPINNER[++s->spin_idx] == '\0')
		s->spin_idx = 0;
	fsl_free(id_str);
	rc = formatln(&wcstr, &width, line, view->ncols, 0);
	fsl_free(line);
	line = NULL;
	if (rc)
		return rc;
	waddwstr(view->window, wcstr);
	fsl_free(wcstr);
	wcstr = NULL;
	if (width < view->ncols - 1)
		waddch(view->window, '\n');

	s->eof = false;
	while (nprinted < view->nlines - 2) {
		linelen = getline(&line, &linesz, blame->f);
		if (linelen == -1) {
			if (feof(blame->f)) {
				s->eof = true;
				break;
			}
			fsl_free(line);
			return RC(ferror(blame->f) ? fsl_errno_to_rc(errno,
			    FSL_RC_IO) : FSL_RC_IO, "%s", "getline");
		}
		if (++lineno < s->first_line_onscreen)
			continue;

		if (view->active && nprinted == s->selected_line - 1)
			wattr_on(view->window, A_REVERSE, NULL);

		if (blame->nlines > 0) {
			blame_line = &blame->lines[lineno - 1];
			if (blame_line->annotated && prev_id &&
			    fsl_uuidcmp(prev_id, blame_line->id) == 0 &&
			    !(view->active &&
			    nprinted == s->selected_line - 1)) {
				waddstr(view->window, "          ");
			} else if (blame_line->annotated) {
				char *id_str;
				id_str = fsl_strndup(blame_line->id,
				    idfield - 1);
				if (id_str == NULL) {
					fsl_free(line);
					return RC(FSL_RC_ERROR, "%s",
					    "fsl_strdup");
				}
				if (s->colour)
					c = get_colour(&s->colours,
					    FNC_COMMIT_ID);
				if (c)
					wattr_on(view->window,
					    COLOR_PAIR(c->scheme), NULL);
				wprintw(view->window, "%.*s", idfield - 1,
				    id_str);
				if (c)
					wattr_off(view->window,
					    COLOR_PAIR(c->scheme), NULL);
				fsl_free(id_str);
				prev_id = blame_line->id;
			} else {
				waddstr(view->window, "..........");
				prev_id = NULL;
			}
		} else {
			waddstr(view->window, "..........");
			prev_id = NULL;
		}

		if (view->active && nprinted == s->selected_line - 1)
			wattr_off(view->window, A_REVERSE, NULL);
		waddstr(view->window, " ");

		if (view->ncols <= idfield) {
			width = idfield;
			wcstr = wcsdup(L"");
			if (wcstr == NULL) {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE),
				    "%s", "wcsdup");
				fsl_free(line);
				return rc;
			}
		} else if (s->first_line_onscreen + nprinted == s->matched_line
		    && regmatch->rm_so >= 0 &&
		    regmatch->rm_so < regmatch->rm_eo) {
			rc = write_matched_line(&width, line,
			    view->ncols - idfield, idfield,
			    view->window, regmatch);
			if (rc) {
				fsl_free(line);
				return rc;
			}
			width += idfield;
		} else {
			rc = formatln(&wcstr, &width, line,
			    view->ncols - idfield, idfield);
			waddwstr(view->window, wcstr);
			fsl_free(wcstr);
			wcstr = NULL;
			width += idfield;
		}

		if (width <= view->ncols - 1)
			waddch(view->window, '\n');
		if (++nprinted == 1)
			s->first_line_onscreen = lineno;
	}
	fsl_free(line);
	s->last_line_onscreen = lineno;

	draw_vborder(view);

	return rc;
}

static int
blame_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_view			*diff_view;
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 start_col = 0, rc = 0;

	switch (ch) {
	case 'q':
		s->done = true;
		if (s->selected_commit)
			fnc_commit_artifact_close(s->selected_commit);
		break;
	case 'c':
		s->colour = !s->colour;
		break;
	case 'g':
		if (!fnc_home(view))
			break;
	case KEY_HOME:
		s->selected_line = 1;
		s->first_line_onscreen = 1;
		break;
	case KEY_END:
	case 'G':
		if (s->blame.nlines < view->nlines - 2) {
			s->selected_line = s->blame.nlines;
			s->first_line_onscreen = 1;
		} else {
			s->selected_line = view->nlines - 2;
			s->first_line_onscreen = s->blame.nlines -
			    (view->nlines - 3);
		}
		break;
	case KEY_UP:
	case 'k':
		if (s->selected_line > 1)
			--s->selected_line;
		else if (s->selected_line == 1 && s->first_line_onscreen > 1)
			--s->first_line_onscreen;
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->first_line_onscreen == 1) {
			s->selected_line = 1;
			break;
		}
		if (s->first_line_onscreen > view->nlines - 2)
			s->first_line_onscreen -= (view->nlines - 2);
		else
			s->first_line_onscreen = 1;
		break;
	case KEY_DOWN:
	case 'j':
		if (s->selected_line < view->nlines - 2 &&
		    s->first_line_onscreen +
		    s->selected_line <= s->blame.nlines)
			++s->selected_line;
		else if (s->last_line_onscreen < s->blame.nlines)
			++s->first_line_onscreen;
		break;
	case 'b':
	case 'p': {
		fsl_uuid_cstr id = NULL;
		id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
		    s->first_line_onscreen, s->selected_line);
		if (id == NULL)
			break;
		if (ch == 'p') {
			fsl_cx		*f = fcli_cx();
			fsl_db		*db = fsl_needs_repo(f);
			fsl_deck	 d = fsl_deck_empty;
			fsl_id_t	 rid = fsl_uuid_to_rid(f, id);
			fsl_uuid_str	 pid = fsl_db_g_text(db, NULL,
			    "SELECT uuid FROM plink, blob WHERE plink.cid=%d "
			    "AND blob.rid=plink.pid AND plink.isprim", rid);
			if (pid == NULL)
				break;
			/* Check file exists in parent check-in. */
			rc = fsl_deck_load_sym(f, &d, pid, FSL_SATYPE_CHECKIN);
			if (rc) {
				fsl_deck_finalize(&d);
				fsl_free(pid);
				return RC(rc, "%s", "fsl_deck_load_sym");
			}
			rc = fsl_deck_F_rewind(&d);
			if (rc) {
				fsl_deck_finalize(&d);
				fsl_free(pid);
				return RC(rc, "%s", "fsl_deck_F_rewind");
			}
			if (fsl_deck_F_search(&d, s->path +
			    (fnc_init.sym ? 0 : 1)) == NULL) {
				char *m = fsl_mprintf("-- %s not in [%.12s] --",
				    s->path + (fnc_init.sym ? 0 : 1), pid);
				if (m == NULL)
					rc = RC(FSL_RC_ERROR, "%s",
					    "fsl_mprintf");
				wattr_on(view->window, A_BOLD, NULL);
				mvwaddstr(view->window,
				    view->start_ln + view->nlines - 1, 0, m);
				wclrtoeol(view->window);
				wattr_off(view->window, A_BOLD, NULL);
				update_panels();
				doupdate();
				sleep(1);
				fsl_deck_finalize(&d);
				fsl_free(pid);
				fsl_free(m);
				break;
			}
			rc = fnc_commit_qid_alloc(&s->blamed_commit, pid);
			if (rc)
				return rc;
		} else {
			if (!fsl_uuidcmp(id, s->blamed_commit->id))
				break;
			rc = fnc_commit_qid_alloc(&s->blamed_commit, id);
		}
		if (rc)
			break;
		s->done = true;
		rc = stop_blame(&s->blame);
		s->done = false;
		if (rc)
			break;
		CONCAT(STAILQ, _INSERT_HEAD)(&s->blamed_commits,
		    s->blamed_commit, entry);
		rc = run_blame(view);
		if (rc)
			break;
		break;
	}
	case KEY_BACKSPACE:
	case 'B': {
		struct fnc_commit_qid *first;
		first = CONCAT(STAILQ, _FIRST)(&s->blamed_commits);
		if (!fsl_uuidcmp(first->id, s->commit_id))
			break;
		s->done = true;
		rc = stop_blame(&s->blame);
		s->done = false;
		if (rc)
			break;
		CONCAT(STAILQ, _REMOVE_HEAD)(&s->blamed_commits, entry);
		fnc_commit_qid_free(s->blamed_commit);
		s->blamed_commit = CONCAT(STAILQ, _FIRST)(&s->blamed_commits);
		rc = run_blame(view);
		if (rc)
			break;
		break;
	}
	case KEY_ENTER:
	case '\r': {
		fsl_cx				*f = fcli_cx();
		struct fnc_commit_artifact	*commit = NULL;
		fsl_stmt			*q = NULL;
		fsl_uuid_cstr			 id = NULL;

		id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
		    s->first_line_onscreen, s->selected_line);
		if (id == NULL)
			break;
		if (s->selected_commit)
			fnc_commit_artifact_close(s->selected_commit);
		if (rc)
			break;
		q = fsl_stmt_malloc();
		rc = commit_builder(&commit, fsl_uuid_to_rid(f, id), q);
		fsl_stmt_finalize(q);
		if (rc) {
			fnc_commit_artifact_close(commit);
			break;
		}
		if (view_is_parent(view))
		    start_col = view_split_start_col(view->start_col);
		diff_view = view_open(0, 0, 0, start_col, FNC_VIEW_DIFF);
		if (diff_view == NULL) {
			fnc_commit_artifact_close(commit);
			rc = RC(FSL_RC_ERROR, "%s", "view_open");
			break;
		}
		rc = open_diff_view(diff_view, commit, DIFF_DEF_CTXT,
		    fnc_init.ws, fnc_init.invert, !fnc_init.quiet, NULL, true,
		    NULL);
		s->selected_commit = commit;
		if (rc) {
			fnc_commit_artifact_close(commit);
			view_close(diff_view);
			break;
		}
		view->active = false;
		diff_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				break;
			view_set_child(view, diff_view);
			view->focus_child = true;
		} else
			*new_view = diff_view;
		if (rc)
			break;
		break;
	}
	case KEY_NPAGE:
	case CTRL('f'):
	case ' ':
		if (s->last_line_onscreen >= s->blame.nlines && s->selected_line
		    >= MIN(s->blame.nlines, view->nlines - 2))
			break;
		if (s->last_line_onscreen >= s->blame.nlines &&
		    s->selected_line < view->nlines - 2) {
			s->selected_line = MIN(s->blame.nlines,
			    view->nlines - 2);
			break;
		}
		if (s->last_line_onscreen + view->nlines - 2 <= s->blame.nlines)
			s->first_line_onscreen += view->nlines - 2;
		else
			s->first_line_onscreen =
			    s->blame.nlines - (view->nlines - 3);
		break;
	case KEY_RESIZE:
		if (s->selected_line > view->nlines - 2) {
			s->selected_line = MIN(s->blame.nlines,
			    view->nlines - 2);
		}
		break;
	default:
		break;
	}
	return rc;
}

static int
blame_search_init(struct fnc_view *view)
{
	struct fnc_blame_view_state *s = &view->state.blame;

	s->matched_line = 0;
	return 0;
}

static int
blame_search_next(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	char				*line = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 lineno;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
		return 0;
	}

	if (s->matched_line) {
		if (view->searching == SEARCH_FORWARD)
			lineno = s->matched_line + 1;
		else
			lineno = s->matched_line - 1;
	} else {
		if (view->searching == SEARCH_FORWARD)
			lineno = 1;
		else
			lineno = s->blame.nlines;
	}

	while (1) {
		off_t offset;

		if (lineno <= 0 || lineno > s->blame.nlines) {
			if (s->matched_line == 0) {
				view->search_status = SEARCH_CONTINUE;
				break;
			}

			if (view->searching == SEARCH_FORWARD)
				lineno = 1;
			else
				lineno = s->blame.nlines;
		}

		offset = s->blame.line_offsets[lineno - 1];
		if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
			fsl_free(line);
			return RC(fsl_errno_to_rc(errno, FSL_RC_IO),
			    "%s", "fseeko");
		}
		linelen = getline(&line, &linesz, s->blame.f);
		if (linelen != -1 && regexec(&view->regex, line, 1,
		    &view->regmatch, 0) == 0) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_line = lineno;
			break;
		}
		if (view->searching == SEARCH_FORWARD)
			++lineno;
		else
			--lineno;
	}
	fsl_free(line);

	if (s->matched_line) {
		s->first_line_onscreen = s->matched_line;
		s->selected_line = 1;
	}

	return 0;
}

static fsl_uuid_cstr
get_selected_commit_id(struct fnc_blame_line *lines, int nlines,
    int first_line_onscreen, int selected_line)
{
	struct fnc_blame_line *line;

	if (nlines <= 0)
		return NULL;

	line = &lines[first_line_onscreen - 1 + selected_line - 1];

	return line->id;
}

static int
fnc_commit_qid_alloc(struct fnc_commit_qid **qid, fsl_uuid_cstr id)
{
	int rc = 0;

	*qid = calloc(1, sizeof(**qid));
	if (*qid == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	(*qid)->id = fsl_strdup(id);
	if ((*qid)->id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		fnc_commit_qid_free(*qid);
		*qid = NULL;
	}

	return rc;
}

static int
close_blame_view(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	struct fsl_list_state		 st = { FNC_COLOUR_OBJ };
	int				 rc = 0;

	rc = stop_blame(&s->blame);

	while (!CONCAT(STAILQ, _EMPTY)(&s->blamed_commits)) {
		struct fnc_commit_qid *blamed_commit;
		blamed_commit = CONCAT(STAILQ, _FIRST)(&s->blamed_commits);
		CONCAT(STAILQ, _REMOVE_HEAD)(&s->blamed_commits, entry);
		fnc_commit_qid_free(blamed_commit);
	}

	fsl_free(s->path);
	fsl_list_clear(&s->colours, fsl_list_object_free, &st);

	return rc;
}

static int
stop_blame(struct fnc_blame *blame)
{
	int idx, rc = 0;

	if (blame->thread_id) {
		int retval;
		rc = pthread_mutex_unlock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		rc = pthread_join(blame->thread_id, (void **)&retval);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_join");
		rc = pthread_mutex_lock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		if (!rc && fsl_cx_err_get_e(fcli_cx())->code == FSL_RC_BREAK) {
			rc = 0;
			fcli_err_reset();
		}
		blame->thread_id = 0;
	}
	if (blame->f) {
		if (fclose(blame->f) == EOF && rc == 0)
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s",
			    fclose);
		blame->f = NULL;
	}
	if (blame->lines) {
		for (idx = 0; idx < blame->nlines; ++idx)
			fsl_free(blame->lines[idx].id);
		fsl_free(blame->lines);
		blame->lines = NULL;
	}

	fsl_free(blame->cb_cx.root_commit);
	blame->cb_cx.root_commit = NULL;
	fsl_free(blame->cb_cx.commit_id);
	blame->cb_cx.commit_id = NULL;
	fsl_free(blame->line_offsets);

	return rc;
}

static int
cancel_blame(void *state)
{
	int	*done = state;
	int	 rc = 0;

	rc = pthread_mutex_lock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");

	if (*done)
		rc = fcli_err_set(FSL_RC_BREAK, "user quit");

	rc = pthread_mutex_unlock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	return rc;
}

static void
fnc_commit_qid_free(struct fnc_commit_qid *qid)
{
	fsl_free(qid->id);
	fsl_free(qid);
}

static int
cmd_branch(fcli_command const *argv)
{
	struct fnc_view	*view;
	char		*glob = NULL;
	double		 dateline;
	int		 branch_flags, rc = 0, when = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	branch_flags = BRANCH_LS_OPEN_CLOSED;
	if (fnc_init.open && fnc_init.closed)
		return RC(FSL_RC_MISUSE, "%s",
		    "--open and --close are mutually exclusive options");
	else if (fnc_init.open)
		branch_flags = BRANCH_LS_OPEN_ONLY;
	else if (fnc_init.closed)
		branch_flags = BRANCH_LS_CLOSED_ONLY;

	if (fnc_init.sort) {
		if (!fsl_strcmp(fnc_init.sort, "mru"))
			FLAG_SET(branch_flags, BRANCH_SORT_MTIME);
		else if (!fsl_strcmp(fnc_init.sort, "state"))
			FLAG_SET(branch_flags, BRANCH_SORT_STATUS);
		else
			return RC(FSL_RC_MISUSE, "invalid sort order: %s",
			    fnc_init.sort);
	}
	if (fnc_init.noprivate)
		FLAG_SET(branch_flags, BRANCH_LS_NO_PRIVATE);
	if (fnc_init.reverse)
		FLAG_SET(branch_flags, BRANCH_SORT_REVERSE);

	if (fnc_init.after && fnc_init.before) {
		return RC(FSL_RC_MISUSE, "%s",
		    "--before and --after are mutually exclusive options");
	} else if (fnc_init.after || fnc_init.before) {
		const char *d = NULL;
		d = fnc_init.after ? fnc_init.after : fnc_init.before;
		when = fnc_init.after ? 1 : -1;
		rc = fnc_date_to_mtime(&dateline, d, when);
		if (rc)
			return rc;
	}
	glob = fsl_strdup(fcli_next_arg(true));

	init_curses();

	view = view_open(0, 0, 0, 0, FNC_VIEW_BRANCH);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_branch_view(view, branch_flags, glob, dateline, when);
	if (rc)
		goto end;

	rc = view_loop(view);
end:
	fnc_free_branches(&view->state.branch);
	fsl_free(glob);
	return rc;
}

static int
open_branch_view(struct fnc_view *view, int branch_flags, const char *glob,
    double dateline, int when)
{
	struct fnc_branch_view_state	*s = &view->state.branch;
	int				 rc = 0;

	s->selected_branch = 0;
	s->colour = !fnc_init.nocolour && has_colors();
	s->branch_flags = branch_flags;
	s->branch_glob = glob;
	s->dateline = dateline;
	s->when = when;

	rc = fnc_load_branches(s);
	if (rc)
		return rc;

	if (s->colour)
		init_pair(FNC_COMMIT_ID, COLOR_GREEN, -1);

	view->show = show_branch_view;
	view->input = branch_input_handler;
	view->close = close_branch_view;
	view->search_init = branch_search_init;
	view->search_next = branch_search_next;

	return 0;
}

static int
fnc_load_branches(struct fnc_branch_view_state *s)
{
	fsl_cx		*const f = fcli_cx();
	fsl_buffer	 sql = fsl_buffer_empty;
	fsl_stmt	*stmt = NULL;
	char		*curr_branch = NULL;
	fsl_id_t	 ckoutrid;
	int		 rc = 0;

	rc = create_tmp_branchlist_table();
	if (rc)
		goto end;

	TAILQ_INIT(&s->branches);
	s->nbranches = 0;

	switch (FLAG_CHK(s->branch_flags, BRANCH_LS_BITMASK)) {
	case BRANCH_LS_OPEN_CLOSED:
		rc = fsl_buffer_append(&sql,
		    "SELECT name, isprivate, isclosed, mtime"
		    " FROM tmp_brlist WHERE 1", -1);
		break;
	case BRANCH_LS_OPEN_ONLY:
		rc = fsl_buffer_append(&sql,
		    "SELECT name, isprivate, isclosed, mtime"
		    " FROM tmp_brlist WHERE NOT isclosed", -1);
		break;
	case BRANCH_LS_CLOSED_ONLY:
		rc = fsl_buffer_append(&sql,
		    "SELECT name, isprivate, isclosed, mtime"
		    " FROM tmp_brlist WHERE isclosed", -1);
		break;
	}
	if (rc)
		goto end;

	if (s->branch_glob) {
		char *like = fsl_mprintf("%%%%%s%%%%", s->branch_glob);
		rc = fsl_buffer_appendf(&sql, " AND name LIKE %Q", like);
		fsl_free(like);
	}
	if (FLAG_CHK(s->branch_flags, BRANCH_LS_NO_PRIVATE))
		rc = fsl_buffer_append(&sql, " AND NOT isprivate", -1);
	if (FLAG_CHK(s->branch_flags, BRANCH_SORT_MTIME))
		rc = fsl_buffer_append(&sql, " ORDER BY -mtime", -1);
	else if (FLAG_CHK(s->branch_flags, BRANCH_SORT_STATUS))
		rc = fsl_buffer_append(&sql, " ORDER BY isclosed", -1);
	else
		rc = fsl_buffer_append(&sql, " ORDER BY name COLLATE nocase",
		    -1);

	if (!rc && (FLAG_CHK(s->branch_flags, BRANCH_SORT_REVERSE)))
		rc = fsl_buffer_append(&sql," DESC", -1);

	stmt = fsl_stmt_malloc();
	if (stmt == NULL)
		goto end;
	if (!rc)
		rc = fsl_cx_prepare(f, stmt, fsl_buffer_cstr(&sql));

	fsl_ckout_version_info(f, &ckoutrid, NULL);
	curr_branch = fsl_db_g_text(fsl_needs_repo(f), NULL,
	    "SELECT value FROM tagxref WHERE rid=%d AND tagid=%d", ckoutrid, 8);

	while (fsl_stmt_step(stmt) == FSL_RC_STEP_ROW) {
		struct fnc_branch *new_branch;
		struct fnc_branchlist_entry *be;
		const char *brname = fsl_stmt_g_text(stmt, 0, NULL);
		bool private = (curr_branch && fsl_stmt_g_int32(stmt, 1) == 1);
		bool open = fsl_stmt_g_int32(stmt, 2) == 0;
		double mtime = fsl_stmt_g_int64(stmt, 3);
		bool curr = curr_branch && !fsl_strcmp(curr_branch, brname);
		if ((s->when > 0 && mtime < s->dateline) ||
		    (s->when < 0 && mtime > s->dateline))
			continue;
		alloc_branch(&new_branch, brname, mtime, open, private, curr);
		fnc_branchlist_insert(&be, &s->branches, new_branch);
		if (be)
			be->idx = s->nbranches++;
	}
	s->first_branch_onscreen = TAILQ_FIRST(&s->branches);

	if (!stmt->rowCount)
		rc = RC(FSL_RC_BREAK, "no matching records: %s",
		    s->branch_glob);
end:
	fsl_stmt_finalize(stmt);
	fsl_free(curr_branch);
	fsl_buffer_clear(&sql);
	return rc;
}

static int
create_tmp_branchlist_table(void)
{
	fsl_cx			*const f = fcli_cx();
	fsl_db			*db = fsl_needs_ckout(f);
	static const char	 tmp_branchlist_table[] =
	    "CREATE TEMP TABLE IF NOT EXISTS tmp_brlist AS "
	    "SELECT tagxref.value AS name,"
	    " max(event.mtime) AS mtime,"
	    " EXISTS(SELECT 1 FROM tagxref AS tx WHERE tx.rid=tagxref.rid"
	    "  AND tx.tagid=(SELECT tagid FROM tag WHERE tagname='closed')"
	    "  AND tx.tagtype > 0) AS isclosed,"
	    " (SELECT tagxref.value FROM plink CROSS JOIN tagxref"
	    "  WHERE plink.pid=event.objid"
	    "  AND tagxref.rid=plink.cid"
	    "  AND tagxref.tagid=(SELECT tagid FROM tag WHERE tagname='branch')"
	    "  AND tagtype>0) AS mergeto,"
	    " count(*) AS nckin,"
	    " (SELECT uuid FROM blob WHERE rid=tagxref.rid) AS ckin,"
	    " event.bgcolor AS bgclr,"
	    " EXISTS(SELECT 1 FROM private WHERE rid=tagxref.rid) AS isprivate "
	    "FROM tagxref, tag, event "
	    "WHERE tagxref.tagid=tag.tagid"
	    " AND tagxref.tagtype>0"
	    " AND tag.tagname='branch'"
	    " AND event.objid=tagxref.rid "
	    "GROUP BY 1;";
	int rc = 0;

	if (!db)
		return RC(FSL_RC_NOT_A_CKOUT, "%s", "fsl_needs_ckout");
	rc = fsl_db_exec(db, tmp_branchlist_table);

	return rc ? RC(fsl_cx_uplift_db_error2(f, db, rc), "%s", "fsl_db_exec")
	    : rc;
}

static int
alloc_branch(struct fnc_branch **branch, const char *name, double mtime,
    bool open, bool priv, bool curr)
{
	fsl_uuid_str	id = NULL;
	char		iso8601[ISO8601_TIMESTAMP], *date = NULL;
	int		rc = 0;

	*branch = calloc(1, sizeof(**branch));
	if (*branch == NULL)
		return RC(FSL_RC_ERROR, "%s", "calloc");

	rc = fsl_sym_to_uuid(fcli_cx(), name, FSL_SATYPE_ANY, &id, NULL);
	if (rc || id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_sym_to_uuid");
		fnc_branch_close(*branch);
		*branch = NULL;
		return rc;
	}

	fsl_julian_to_iso8601(mtime, iso8601, false);
	date = fsl_mprintf("%.*s", ISO8601_DATE_ONLY, iso8601);

	(*branch)->id = id;
	(*branch)->name = fsl_strdup(name);
	(*branch)->date = date;
	(*branch)->open = open;
	(*branch)->private = priv;
	(*branch)->current = curr;
	if ((*branch)->name == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		fnc_branch_close(*branch);
		*branch = NULL;
	}

	return rc;
}

static int
fnc_branchlist_insert(struct fnc_branchlist_entry **newp,
    struct fnc_branchlist_head *branches, struct fnc_branch *branch)
{
	struct fnc_branchlist_entry *new, *be;

	*newp = NULL;

	new = fsl_malloc(sizeof(*new));
	if (new == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	new->branch = branch;
	*newp = new;

	be = TAILQ_LAST(branches, fnc_branchlist_head);
	if (!be) {
		/* Empty list; add first branch. */
		TAILQ_INSERT_HEAD(branches, new, entries);
		return 0;
	}

	/*
	 * Deduplicate (extremely unlikely or impossible?) entries on insert.
	 * Don't force lexicographical order; we already retrieved the branch
	 * names from the database using a query to obtain (a) lexicographical
	 * or (b) user-specified sorted results (i.e., MRU or LRU).
	 */
	while (be) {
		if (!fsl_strcmp(be->branch->name, new->branch->name)) {
			/* Duplicate entry. */
			fsl_free(new);
			*newp = NULL;
			return 0;
		}
		be = TAILQ_PREV(be, fnc_branchlist_head, entries);
	}

	/* No duplicates; add to end of list. */
	TAILQ_INSERT_TAIL(branches, new, entries);
	return 0;
}

static int
show_branch_view(struct fnc_view *view)
{
	struct fnc_branch_view_state	*s = &view->state.branch;
	struct fnc_branchlist_entry	*be;
	char				*line = NULL;
	wchar_t				*wline;
	int				 limit, n, width, rc = 0;

	werase(view->window);
	s->ndisplayed = 0;

	limit = view->nlines;
	if (limit == 0)
		return rc;

	be = s->first_branch_onscreen;

	if ((line = fsl_mprintf("branches [%d/%d]", be->idx + s->selected + 1,
	    s->nbranches)) == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");

	rc = formatln(&wline, &width, line, view->ncols, 0);
	if (rc) {
		fsl_free(line);
		return rc;
	}
	if (screen_is_shared(view))
		wstandout(view->window);
	waddwstr(view->window, wline);
	if (screen_is_shared(view))
		wstandend(view->window);
	fsl_free(wline);
	wline = NULL;
	fsl_free(line);
	line = NULL;
	if (width < view->ncols - 1)
		waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;

	n = 0;
	while (be && limit > 0) {
		char *line = NULL;

		line = fsl_mprintf(" %c%s%s%s%s%s%s%c %s",
		    be->branch->open ? '+' : '-', be->branch->name,
		    be->branch->private ? "*" : "",
		    be->branch->current ? "@" : "", s->show_id ?  " [" : "",
		    s->show_id ? be->branch->id : "", s->show_id ? "]" : "",
		    s->show_date ? ':' : 0,
		    s->show_date ? be->branch->date : 0);
		if (line == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");

		rc = formatln(&wline, &width, line, view->ncols, 0);
		if (rc) {
			fsl_free(line);
			return rc;
		}

		if (n == s->selected) {
			if (view->active)
				wattr_on(view->window, A_REVERSE, NULL);
			s->selected_branch = be;
		}
		if (s->colour)
			wattr_on(view->window, COLOR_PAIR(FNC_COMMIT_ID), NULL);
		waddwstr(view->window, wline);
		if (s->colour)
			wattr_off(view->window, COLOR_PAIR(FNC_COMMIT_ID), NULL);
		if (width < view->ncols - 1)
			waddch(view->window, '\n');
		if (n == s->selected && view->active)
			wattr_off(view->window, A_REVERSE, NULL);

		fsl_free(line);
		fsl_free(wline);
		wline = NULL;
		++n;
		++s->ndisplayed;
		--limit;
		s->last_branch_onscreen = be;
		be = TAILQ_NEXT(be, entries);
	}

	draw_vborder(view);
	return rc;
}

static int
branch_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_branch_view_state	*s = &view->state.branch;
	struct fnc_view			*timeline_view, *tree_view;
	struct fnc_branchlist_entry	*be;
	int				 start_col = 0, n, rc = 0;

	switch (ch) {
	case 'c':
		s->colour = !s->colour;
		break;
	case 'd':
		s->show_date = !s->show_date;
		break;
	case 'i':
		s->show_id = !s->show_id;
		break;
	case KEY_ENTER:
	case '\r':
	case ' ':
		if (!s->selected_branch)
			break;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		rc = tl_branch_entry(&timeline_view, start_col,
		    s->selected_branch);
		view->active = false;
		timeline_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				return rc;
			view_set_child(view, timeline_view);
			view->focus_child = true;
		} else
			*new_view = timeline_view;
		break;
	case 't':
		if (!s->selected_branch)
			break;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		rc = browse_branch_tree(&tree_view, start_col,
		    s->selected_branch);
		if (rc || tree_view == NULL)
			break;
		view->active = false;
		tree_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				return rc;
			view_set_child(view, tree_view);
			view->focus_child = true;
		} else
			*new_view = tree_view;
		break;
	case 'g':
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	case KEY_HOME:
		s->selected = 0;
		s->first_branch_onscreen = TAILQ_FIRST(&s->branches);
		break;
	case KEY_END:
	case 'G':
		s->selected = 0;
		be = TAILQ_LAST(&s->branches, fnc_branchlist_head);
		for (n = 0; n < view->nlines - 1; ++n) {
			if (be == NULL)
				break;
			s->first_branch_onscreen = be;
			be = TAILQ_PREV(be, fnc_branchlist_head, entries);
		}
		if (n > 0)
			s->selected = n - 1;
		break;
	case KEY_UP:
	case 'k':
		if (s->selected > 0) {
			--s->selected;
			break;
		}
		branch_scroll_up(s, 1);
		break;
	case KEY_DOWN:
	case 'j':
		if (s->selected < s->ndisplayed - 1) {
			++s->selected;
			break;
		}
		if (TAILQ_NEXT(s->last_branch_onscreen, entries) == NULL)
			/* Reached last entry. */
			break;
		branch_scroll_down(s, 1);
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->first_branch_onscreen == TAILQ_FIRST(&s->branches))
			s->selected = 0;
		branch_scroll_up(s, MAX(0, view->nlines - 1));
		break;
	case KEY_NPAGE:
	case CTRL('f'):
		if (TAILQ_NEXT(s->last_branch_onscreen, entries) == NULL) {
			/* No more entries off-page; move cursor down. */
			if (s->selected < s->ndisplayed - 1)
				s->selected = s->ndisplayed - 1;
			break;
		}
		branch_scroll_down(s, view->nlines - 1);
		break;
	case CTRL('l'):
	case 'R':
		fnc_free_branches(s);
		s->branch_glob = NULL; /* Shared pointer. */
		s->when = 0;
		s->branch_flags = BRANCH_LS_OPEN_CLOSED;
		rc = fnc_load_branches(s);
		break;
	case KEY_RESIZE:
		if (view->nlines >= 2 && s->selected >= view->nlines - 1)
			s->selected = view->nlines - 2;
		break;
	default:
		break;
	}

	return rc;
}

static int
tl_branch_entry(struct fnc_view **new_view, int start_col,
    struct fnc_branchlist_entry *be)
{
	struct fnc_view	*timeline_view;
	fsl_id_t	 rid;
	int		 rc = 0;

	*new_view = NULL;

	rid = fsl_uuid_to_rid(fcli_cx(), be->branch->id);
	if (rid < 0)
		return RC(rc, "%s", "fsl_uuid_to_rid");

	timeline_view = view_open(0, 0, 0, start_col, FNC_VIEW_TIMELINE);
	if (timeline_view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_timeline_view(timeline_view, rid, "/");
end:
	if (rc)
		view_close(timeline_view);
	else
		*new_view = timeline_view;
	return rc;
}

static int
browse_branch_tree(struct fnc_view **new_view, int start_col,
    struct fnc_branchlist_entry *be)
{
	struct fnc_view	*tree_view;
	fsl_id_t	 rid;
	int		 rc = 0;

	*new_view = NULL;

	rid = fsl_uuid_to_rid(fcli_cx(), be->branch->id);
	if (rid < 0)
		return RC(rc, "%s", "fsl_uuid_to_rid");

	tree_view = view_open(0, 0, 0, start_col, FNC_VIEW_TREE);
	if (tree_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_tree_view(tree_view, "/", rid);
	if (!rc)
		*new_view = tree_view;
	return rc;
}

static void
branch_scroll_up(struct fnc_branch_view_state *s, int maxscroll)
{
	struct fnc_branchlist_entry	*be;
	int				 idx = 0;

	if (s->first_branch_onscreen == TAILQ_FIRST(&s->branches))
		return;

	be = TAILQ_PREV(s->first_branch_onscreen, fnc_branchlist_head, entries);
	while (idx++ < maxscroll) {
		if (be == NULL)
			break;
		s->first_branch_onscreen = be;
		be = TAILQ_PREV(be, fnc_branchlist_head, entries);
	}
}

static void
branch_scroll_down(struct fnc_branch_view_state *s, int maxscroll)
{
	struct fnc_branchlist_entry	*next, *last;
	int				 idx = 0;

	if (s->first_branch_onscreen)
		next = TAILQ_NEXT(s->first_branch_onscreen, entries);
	else
		next = TAILQ_FIRST(&s->branches);

	last = s->last_branch_onscreen;
	while (next && last && idx++ < maxscroll) {
		last = TAILQ_NEXT(last, entries);
		if (last) {
			s->first_branch_onscreen = next;
			next = TAILQ_NEXT(next, entries);
		}
	}
}

static int
branch_search_init(struct fnc_view *view)
{
	struct fnc_branch_view_state *s = &view->state.branch;

	s->matched_branch = NULL;
	return 0;
}

static int
branch_search_next(struct fnc_view *view)
{
	struct fnc_branch_view_state	*s = &view->state.branch;
	struct fnc_branchlist_entry	*be = NULL;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
		return 0;
	}

	if (s->matched_branch) {
		if (view->searching == SEARCH_FORWARD) {
			if (s->selected_branch)
				be = TAILQ_NEXT(s->selected_branch, entries);
			else
				be = TAILQ_PREV(s->selected_branch,
				    fnc_branchlist_head, entries);
		} else {
			if (s->selected_branch == NULL)
				be = TAILQ_LAST(&s->branches,
				    fnc_branchlist_head);
			else
				be = TAILQ_PREV(s->selected_branch,
				    fnc_branchlist_head, entries);
		}
	} else {
		if (view->searching == SEARCH_FORWARD)
			be = TAILQ_FIRST(&s->branches);
		else
			be = TAILQ_LAST(&s->branches, fnc_branchlist_head);
	}

	while (1) {
		if (be == NULL) {
			if (s->matched_branch == NULL) {
				view->search_status = SEARCH_CONTINUE;
				return 0;
			}
			if (view->searching == SEARCH_FORWARD)
				be = TAILQ_FIRST(&s->branches);
			else
				be = TAILQ_LAST(&s->branches,
				    fnc_branchlist_head);
		}

		if (match_branchlist_entry(be, &view->regex)) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_branch = be;
			break;
		}

		if (view->searching == SEARCH_FORWARD)
			be = TAILQ_NEXT(be, entries);
		else
			be = TAILQ_PREV(be, fnc_branchlist_head, entries);
	}

	if (s->matched_branch) {
		s->first_branch_onscreen = s->matched_branch;
		s->selected = 0;
	}

	return 0;
}

static int
match_branchlist_entry(struct fnc_branchlist_entry *be, regex_t *regex)
{
	regmatch_t regmatch;

	return regexec(regex, be->branch->name, 1, &regmatch, 0) == 0;
}

static int
close_branch_view(struct fnc_view *view)
{
	struct fnc_branch_view_state *s = &view->state.branch;

	fnc_free_branches(s);

	return 0;
}

static void
fnc_free_branches(struct fnc_branch_view_state *s)
{
	struct fnc_branchlist_entry *be;

	while (!TAILQ_EMPTY(&s->branches)) {
		be = TAILQ_FIRST(&s->branches);
		TAILQ_REMOVE(&s->branches, be, entries);
		fnc_branch_close(be->branch);
		fsl_free(be);
	}
}

static void
fnc_branch_close(struct fnc_branch *branch)
{
	fsl_free(branch->name);
	fsl_free(branch->date);
	fsl_free(branch->id);
	fsl_free(branch);
}

/*
 * Assign path to **inserted->path, with optional ->data assignment, and insert
 * in lexicographically sorted order into the doubly-linked list rooted at
 * *pathlist. If path is not unique, return without adding a duplicate entry.
 */
static int
fnc_pathlist_insert(struct fnc_pathlist_entry **inserted,
    struct fnc_pathlist_head *pathlist, const char *path, void *data)
{
	struct fnc_pathlist_entry	*new, *pe;
	int				 rc = 0;

	if (inserted)
		*inserted = NULL;

	new = fsl_malloc(sizeof(*new));
	if (new == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	new->path = path;
	new->pathlen = fsl_strlen(path);
	new->data = data;

	/*
	 * Most likely, supplied paths will be sorted (e.g., fnc diff *.c), so
	 * post-order traversal will be more efficient when inserting entries.
	 */
	pe = TAILQ_LAST(pathlist, fnc_pathlist_head);
	while (pe) {
		int cmp = fnc_path_cmp(pe->path, new->path, pe->pathlen,
		    new->pathlen);
		if (cmp == 0) {
			fsl_free(new);  /* Duplicate path; don't insert. */
			return rc;
		} else if (cmp < 0) {
			TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
			if (inserted)
				*inserted = new;
			return rc;
		}
		pe = TAILQ_PREV(pe, fnc_pathlist_head, entry);
	}

	TAILQ_INSERT_HEAD(pathlist, new, entry);
	if (inserted)
		*inserted = new;
	return rc;
}

static int
fnc_path_cmp(const char *path1, const char *path2, size_t len1, size_t len2)
{
	size_t	minlen;
	size_t	idx = 0;

	/* Trim any leading path separators. */
	while (path1[0] == '/') {
		++path1;
		--len1;
	}
	while (path2[0] == '/') {
		++path2;
		--len2;
	}
	minlen = MIN(len1, len2);

	/* Skip common prefix. */
	while (idx < minlen && path1[idx] == path2[idx])
		++idx;

	/* Are path lengths exactly equal (exluding path separators)? */
	if (len1 == len2 && idx >= minlen)
		return 0;

	/* Trim any redundant trailing path seperators. */
	while (path1[idx] == '/' && path1[idx + 1] == '/')
		++path1;
	while (path2[idx] == '/' && path2[idx + 1] == '/')
		++path2;

	/* Ignore trailing path separators. */
	if (path1[idx] == '/' && path1[idx + 1] == '\0' && path2[idx] == '\0')
		return 0;
	if (path2[idx] == '/' && path2[idx + 1] == '\0' && path1[idx] == '\0')
		return 0;

	/* Order children in subdirectories directly after their parents. */
	if (path1[idx] == '/' && path2[idx] == '\0')
		return 1;
	if (path2[idx] == '/' && path1[idx] == '\0')
		return -1;
	if (path1[idx] == '/' && path2[idx] != '\0')
		return -1;
	if (path2[idx] == '/' && path1[idx] != '\0')
		return 1;

	/* Character immediately after the common prefix determines order. */
	return (unsigned char)path1[idx] < (unsigned char)path2[idx] ? -1 : 1;
}

static void
fnc_pathlist_free(struct fnc_pathlist_head *pathlist)
{
	struct fnc_pathlist_entry *pe;

	while ((pe = TAILQ_FIRST(pathlist)) != NULL) {
		TAILQ_REMOVE(pathlist, pe, entry);
		free(pe);
	}
}

static void
fnc_show_version(void)
{
	printf("%s %s\n", fcli_progname(), PRINT_VERSION);
}

static int
strtonumcheck(int *ret, const char *nstr, const int min, const int max)
{
	const char	*ptr;
	int		 n;

	ptr = NULL;
	errno = 0;

	n = strtonum(nstr, min, max, &ptr);
	if (errno == ERANGE)
		return RC(FSL_RC_RANGE, "<n> out of range: -n|--limit=%s [%s]",
		    nstr, ptr);
	else if (errno != 0 || errno == EINVAL)
		return RC(FSL_RC_MISUSE, "<n> not a number: -n|--limit=%s [%s]",
		    nstr, ptr);
	else if (ptr && *ptr != '\0')
		return RC(FSL_RC_MISUSE,
		    "invalid char in <n>: -n|--limit=%s [%s]", nstr, ptr);

	*ret = n;
	return 0;
}

/*
 * Attempt to parse string d, which must resemble either an ISO8601 formatted
 * date (e.g., 2021-10-10, 2020-01-01T10:10:10), disgregarding any trailing
 * garbage or space characters such that "2021-10-10x" or "2020-01-01 10:10:10"
 * will pass, or an _unambiguous_ DD/MM/YYYY or MM/DD/YYYY formatted date. Upon
 * success, use when to determine which time component to add to the date (i.e.,
 * 1 sec before or after midnight), and convert to an mtime suitable for
 * comparisons with repository mtime fields and assign to *ret. Upon failure,
 * the error state will be updated with an appropriate error message and code.
 */
static int
fnc_date_to_mtime(double *ret, const char *d, int when)
{
	struct tm	t = {0, 0, 0, 0, 0, 0};
	char		iso8601[ISO8601_TIMESTAMP];

	/* Fill the tm structure. */
	if (strptime(d, "%Y-%m-%d", &t) == NULL) {
		/* If not YYYY-MM-DD, try MM/DD/YYYY and DD/MM/YYYY. */
		if (strptime(d, "%D", &t) != NULL) {
			/* If MM/DD/YYYY, check if it could be DD/MM/YYYY too */
			if (strptime(d, "%d/%m/%Y", &t) != NULL)
				return RC(FSL_RC_AMBIGUOUS,
				    "ambiguous date [%s]", d);
		} else if (strptime(d, "%d/%m/%Y", &t) != NULL) {
			/* If DD/MM/YYYY, check if it could be MM/DD/YYYY too */
			if (strptime(d, "%D", &t) != NULL)
				return RC(FSL_RC_AMBIGUOUS,
				    "ambiguous date [%s]", d);
		} else
			return RC(FSL_RC_TYPE, "unable to parse date: %s", d);
	}

	/* Format tm into ISO8601 string then convert to mtime. */
	if (when > 0)	/* After date d. */
		strftime(iso8601, ISO8601_TIMESTAMP, "%FT23:59:59", &t);
	else		/* Before date d. */
		strftime(iso8601, ISO8601_TIMESTAMP, "%FT00:00:01", &t);
	if (!fsl_iso8601_to_julian(iso8601, ret))
		return RC(FSL_RC_ERROR, "fsl_iso8601_to_julian(%s)", iso8601);

	return 0;
}

static char *
fnc_strsep(char **ptr, const char *sep)
{
	char	*s, *token;

	if ((s = *ptr) == NULL)
		return NULL;

	if (*(token = s + strcspn(s, sep)) != '\0') {
		*token++ = '\0';
		*ptr = token;
	} else
		*ptr = NULL;

	return s;
}

Deleted src/libfossil-config.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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














































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
#if !defined(_NET_FOSSIL_SCM_FSL_AMALGAMATION_CONFIG_H_INCLUDED_)
#define _NET_FOSSIL_SCM_FSL_AMALGAMATION_CONFIG_H_INCLUDED_ 1
#define FSL_AUX_SCHEMA "2015-01-24"
#define FSL_CONTENT_SCHEMA "2"
#define FSL_PACKAGE_NAME "libfossil"
#define FSL_LIBRARY_VERSION "0.0.1-alphabeta"
/* Tweak the following for your system... */
#if !defined(HAVE_COMPRESS)
#  define HAVE_COMPRESS 1
#endif
#if !defined(HAVE_DLFCN_H)
#  define HAVE_DLFCN_H 0
#endif
#if !defined(HAVE_DLOPEN)
#  define HAVE_DLOPEN 0
#endif
#if !defined(HAVE_GETADDRINFO)
#  define HAVE_GETADDRINFO 0
#endif
#if !defined(HAVE_INET_NTOP)
#  define HAVE_INET_NTOP 0
#endif
#if !defined(HAVE_INTTYPES_H)
#  define HAVE_INTTYPES_H 0
#endif
#if !defined(HAVE_LIBDL)
#  define HAVE_LIBDL 0
#endif
#if !defined(HAVE_LIBLTDL)
#  define HAVE_LIBLTDL 0
#endif
#if !defined(_WIN32)
#if !defined(HAVE_LSTAT)
#  define HAVE_LSTAT 1
#endif
#if !defined(HAVE_LTDL_H)
#  define HAVE_LTDL_H 0
#endif
#if !defined(HAVE_LT_DLOPEN)
#  define HAVE_LT_DLOPEN 0
#endif
#if !defined(HAVE_OPENDIR)
#  define HAVE_OPENDIR 1
#endif
#if !defined(HAVE_PIPE)
#  define HAVE_PIPE 1
#endif
#if !defined(HAVE_STAT)
#  define HAVE_STAT 1
#endif
#if !defined(HAVE_STDINT_H)
#  define HAVE_STDINT_H 1
#endif
#if !defined(_DEFAULT_SOURCE)
#  define _DEFAULT_SOURCE 1
#endif
#if !defined(_XOPEN_SOURCE)
#  define _XOPEN_SOURCE 500
#endif
#else
#if !defined(HAVE_LSTAT)
#  define HAVE_LSTAT 0
#endif
#if !defined(HAVE_LTDL_H)
#  define HAVE_LTDL_H 0
#endif
#if !defined(HAVE_LT_DLOPEN)
#  define HAVE_LT_DLOPEN 0
#endif
#if !defined(HAVE_OPENDIR)
#  define HAVE_OPENDIR 1
#endif
#if !defined(HAVE_PIPE)
#  define HAVE_PIPE 0
#endif
#if !defined(HAVE_STAT)
#  define HAVE_STAT 0
#endif
#if !defined(HAVE_STDINT_H)
#  define HAVE_STDINT_H 1
#endif
#endif
/* _WIN32 */


#define FSL_LIB_VERSION_HASH "acbd39275f0d573a74d996caea7918afafff2ff7"
#define FSL_LIB_VERSION_TIMESTAMP "2021-10-08 03:15:51.855 UTC"
#define FSL_LIB_CONFIG_TIME "2021-10-08 04:07 GMT"
#if defined(_MSC_VER)
#define FSL_PLATFORM_OS "windows"
#define FSL_PLATFORM_IS_WINDOWS 1
#define FSL_PLATFORM_IS_UNIX 0
#define FSL_PLATFORM_PLATFORM "windows"
#define FSL_PLATFORM_PATH_SEPARATOR ";"
#define FSL_CHECKOUTDB_NAME "./_FOSSIL_"
/* define a __func__ compatibility macro */
#if _MSC_VER < 1500    /* (vc9.0; dev studio 2008) */
/* sorry; cant do much better than nothing at all on those earlier ones */
#define __func__ "(func)"
#else
#define __func__ __FUNCTION__
#endif
/* for the time being at least, don't complain about there being secure crt alternatives: */
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
/* for the time being at least, don't complain about using POSIX names instead of ISO C++: */
#pragma warning ( disable : 4996 )
/* for the time being at least, suppresss some int conversion warnings */
#pragma warning ( disable : 4244 )     /*'fsl_size_t' to 'int'; this masks other problems that should be fixed*/
#pragma warning ( disable : 4761 )     /*'integral size mismatch in argument'; more size_t problems*/
#pragma warning ( disable : 4267 )     /*'size_t' to 'int'; crops up especially in 64-bit builds*/
/* these were extracted from fossil's unistd.h */
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#include <io.h>
#elif defined(__MINGW32__)
#define FSL_PLATFORM_OS "mingw"
#define FSL_PLATFORM_IS_WINDOWS 1
#define FSL_PLATFORM_IS_UNIX 0
#define FSL_PLATFORM_PLATFORM "windows"
#define FSL_PLATFORM_PATH_SEPARATOR ";"
#define FSL_CHECKOUTDB_NAME "./.fslckout"
#elif defined(__CYGWIN__)
#define FSL_PLATFORM_OS "cygwin"
#define FSL_PLATFORM_IS_WINDOWS 0
#define FSL_PLATFORM_IS_UNIX 1
#define FSL_PLATFORM_PLATFORM "unix"
#define FSL_PLATFORM_PATH_SEPARATOR ":"
#define FSL_CHECKOUTDB_NAME "./_FOSSIL_"
#else
#define FSL_PLATFORM_OS "unknown"
#define FSL_PLATFORM_IS_WINDOWS 0
#define FSL_PLATFORM_IS_UNIX 1
#define FSL_PLATFORM_PLATFORM "unix"
#define FSL_PLATFORM_PATH_SEPARATOR ":"
#define FSL_CHECKOUTDB_NAME "./.fslckout"
#endif


#endif
/* _NET_FOSSIL_SCM_FSL_AMALGAMATION_CONFIG_H_INCLUDED_ */

Deleted src/libfossil.c.

more than 10,000 changes

Deleted src/libfossil.h.

more than 10,000 changes

Deleted src/sqlite3.c.

more than 10,000 changes

Deleted src/sqlite3.h.

more than 10,000 changes

Deleted src/sqlite3ext.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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























































































































































































































































































































































































































































































































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
/*
** 2006 June 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the SQLite interface for use by
** shared libraries that want to be imported as extensions into
** an SQLite instance.  Shared libraries that intend to be loaded
** as extensions by SQLite should #include this file instead of 
** sqlite3.h.
*/
#ifndef SQLITE3EXT_H
#define SQLITE3EXT_H
#include "sqlite3.h"

/*
** The following structure holds pointers to all of the SQLite API
** routines.
**
** WARNING:  In order to maintain backwards compatibility, add new
** interfaces to the end of this structure only.  If you insert new
** interfaces in the middle of this structure, then older different
** versions of SQLite will not be able to load each other's shared
** libraries!
*/
struct sqlite3_api_routines {
  void * (*aggregate_context)(sqlite3_context*,int nBytes);
  int  (*aggregate_count)(sqlite3_context*);
  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  int  (*bind_double)(sqlite3_stmt*,int,double);
  int  (*bind_int)(sqlite3_stmt*,int,int);
  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  int  (*bind_null)(sqlite3_stmt*,int);
  int  (*bind_parameter_count)(sqlite3_stmt*);
  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  int  (*busy_timeout)(sqlite3*,int ms);
  int  (*changes)(sqlite3*);
  int  (*close)(sqlite3*);
  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
                           int eTextRep,const char*));
  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
                             int eTextRep,const void*));
  const void * (*column_blob)(sqlite3_stmt*,int iCol);
  int  (*column_bytes)(sqlite3_stmt*,int iCol);
  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
  int  (*column_count)(sqlite3_stmt*pStmt);
  const char * (*column_database_name)(sqlite3_stmt*,int);
  const void * (*column_database_name16)(sqlite3_stmt*,int);
  const char * (*column_decltype)(sqlite3_stmt*,int i);
  const void * (*column_decltype16)(sqlite3_stmt*,int);
  double  (*column_double)(sqlite3_stmt*,int iCol);
  int  (*column_int)(sqlite3_stmt*,int iCol);
  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
  const char * (*column_name)(sqlite3_stmt*,int);
  const void * (*column_name16)(sqlite3_stmt*,int);
  const char * (*column_origin_name)(sqlite3_stmt*,int);
  const void * (*column_origin_name16)(sqlite3_stmt*,int);
  const char * (*column_table_name)(sqlite3_stmt*,int);
  const void * (*column_table_name16)(sqlite3_stmt*,int);
  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  const void * (*column_text16)(sqlite3_stmt*,int iCol);
  int  (*column_type)(sqlite3_stmt*,int iCol);
  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  int  (*complete)(const char*sql);
  int  (*complete16)(const void*sql);
  int  (*create_collation)(sqlite3*,const char*,int,void*,
                           int(*)(void*,int,const void*,int,const void*));
  int  (*create_collation16)(sqlite3*,const void*,int,void*,
                             int(*)(void*,int,const void*,int,const void*));
  int  (*create_function)(sqlite3*,const char*,int,int,void*,
                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
                          void (*xFinal)(sqlite3_context*));
  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
                            void (*xFinal)(sqlite3_context*));
  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  int  (*data_count)(sqlite3_stmt*pStmt);
  sqlite3 * (*db_handle)(sqlite3_stmt*);
  int (*declare_vtab)(sqlite3*,const char*);
  int  (*enable_shared_cache)(int);
  int  (*errcode)(sqlite3*db);
  const char * (*errmsg)(sqlite3*);
  const void * (*errmsg16)(sqlite3*);
  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  int  (*expired)(sqlite3_stmt*);
  int  (*finalize)(sqlite3_stmt*pStmt);
  void  (*free)(void*);
  void  (*free_table)(char**result);
  int  (*get_autocommit)(sqlite3*);
  void * (*get_auxdata)(sqlite3_context*,int);
  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  int  (*global_recover)(void);
  void  (*interruptx)(sqlite3*);
  sqlite_int64  (*last_insert_rowid)(sqlite3*);
  const char * (*libversion)(void);
  int  (*libversion_number)(void);
  void *(*malloc)(int);
  char * (*mprintf)(const char*,...);
  int  (*open)(const char*,sqlite3**);
  int  (*open16)(const void*,sqlite3**);
  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  void *(*realloc)(void*,int);
  int  (*reset)(sqlite3_stmt*pStmt);
  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_double)(sqlite3_context*,double);
  void  (*result_error)(sqlite3_context*,const char*,int);
  void  (*result_error16)(sqlite3_context*,const void*,int);
  void  (*result_int)(sqlite3_context*,int);
  void  (*result_int64)(sqlite3_context*,sqlite_int64);
  void  (*result_null)(sqlite3_context*);
  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_value)(sqlite3_context*,sqlite3_value*);
  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
                         const char*,const char*),void*);
  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  char * (*xsnprintf)(int,char*,const char*,...);
  int  (*step)(sqlite3_stmt*);
  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
                                char const**,char const**,int*,int*,int*);
  void  (*thread_cleanup)(void);
  int  (*total_changes)(sqlite3*);
  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
                                         sqlite_int64),void*);
  void * (*user_data)(sqlite3_context*);
  const void * (*value_blob)(sqlite3_value*);
  int  (*value_bytes)(sqlite3_value*);
  int  (*value_bytes16)(sqlite3_value*);
  double  (*value_double)(sqlite3_value*);
  int  (*value_int)(sqlite3_value*);
  sqlite_int64  (*value_int64)(sqlite3_value*);
  int  (*value_numeric_type)(sqlite3_value*);
  const unsigned char * (*value_text)(sqlite3_value*);
  const void * (*value_text16)(sqlite3_value*);
  const void * (*value_text16be)(sqlite3_value*);
  const void * (*value_text16le)(sqlite3_value*);
  int  (*value_type)(sqlite3_value*);
  char *(*vmprintf)(const char*,va_list);
  /* Added ??? */
  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  /* Added by 3.3.13 */
  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  int (*clear_bindings)(sqlite3_stmt*);
  /* Added by 3.4.1 */
  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
                          void (*xDestroy)(void *));
  /* Added by 3.5.0 */
  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  int (*blob_bytes)(sqlite3_blob*);
  int (*blob_close)(sqlite3_blob*);
  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
                   int,sqlite3_blob**);
  int (*blob_read)(sqlite3_blob*,void*,int,int);
  int (*blob_write)(sqlite3_blob*,const void*,int,int);
  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
                             int(*)(void*,int,const void*,int,const void*),
                             void(*)(void*));
  int (*file_control)(sqlite3*,const char*,int,void*);
  sqlite3_int64 (*memory_highwater)(int);
  sqlite3_int64 (*memory_used)(void);
  sqlite3_mutex *(*mutex_alloc)(int);
  void (*mutex_enter)(sqlite3_mutex*);
  void (*mutex_free)(sqlite3_mutex*);
  void (*mutex_leave)(sqlite3_mutex*);
  int (*mutex_try)(sqlite3_mutex*);
  int (*open_v2)(const char*,sqlite3**,int,const char*);
  int (*release_memory)(int);
  void (*result_error_nomem)(sqlite3_context*);
  void (*result_error_toobig)(sqlite3_context*);
  int (*sleep)(int);
  void (*soft_heap_limit)(int);
  sqlite3_vfs *(*vfs_find)(const char*);
  int (*vfs_register)(sqlite3_vfs*,int);
  int (*vfs_unregister)(sqlite3_vfs*);
  int (*xthreadsafe)(void);
  void (*result_zeroblob)(sqlite3_context*,int);
  void (*result_error_code)(sqlite3_context*,int);
  int (*test_control)(int, ...);
  void (*randomness)(int,void*);
  sqlite3 *(*context_db_handle)(sqlite3_context*);
  int (*extended_result_codes)(sqlite3*,int);
  int (*limit)(sqlite3*,int,int);
  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  const char *(*sql)(sqlite3_stmt*);
  int (*status)(int,int*,int*,int);
  int (*backup_finish)(sqlite3_backup*);
  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  int (*backup_pagecount)(sqlite3_backup*);
  int (*backup_remaining)(sqlite3_backup*);
  int (*backup_step)(sqlite3_backup*,int);
  const char *(*compileoption_get)(int);
  int (*compileoption_used)(const char*);
  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
                            void (*xFinal)(sqlite3_context*),
                            void(*xDestroy)(void*));
  int (*db_config)(sqlite3*,int,...);
  sqlite3_mutex *(*db_mutex)(sqlite3*);
  int (*db_status)(sqlite3*,int,int*,int*,int);
  int (*extended_errcode)(sqlite3*);
  void (*log)(int,const char*,...);
  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  const char *(*sourceid)(void);
  int (*stmt_status)(sqlite3_stmt*,int,int);
  int (*strnicmp)(const char*,const char*,int);
  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  int (*wal_autocheckpoint)(sqlite3*,int);
  int (*wal_checkpoint)(sqlite3*,const char*);
  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  int (*vtab_config)(sqlite3*,int op,...);
  int (*vtab_on_conflict)(sqlite3*);
  /* Version 3.7.16 and later */
  int (*close_v2)(sqlite3*);
  const char *(*db_filename)(sqlite3*,const char*);
  int (*db_readonly)(sqlite3*,const char*);
  int (*db_release_memory)(sqlite3*);
  const char *(*errstr)(int);
  int (*stmt_busy)(sqlite3_stmt*);
  int (*stmt_readonly)(sqlite3_stmt*);
  int (*stricmp)(const char*,const char*);
  int (*uri_boolean)(const char*,const char*,int);
  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  const char *(*uri_parameter)(const char*,const char*);
  char *(*xvsnprintf)(int,char*,const char*,va_list);
  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  /* Version 3.8.7 and later */
  int (*auto_extension)(void(*)(void));
  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
                     void(*)(void*));
  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
                      void(*)(void*),unsigned char);
  int (*cancel_auto_extension)(void(*)(void));
  int (*load_extension)(sqlite3*,const char*,const char*,char**);
  void *(*malloc64)(sqlite3_uint64);
  sqlite3_uint64 (*msize)(void*);
  void *(*realloc64)(void*,sqlite3_uint64);
  void (*reset_auto_extension)(void);
  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
                        void(*)(void*));
  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
                         void(*)(void*), unsigned char);
  int (*strglob)(const char*,const char*);
  /* Version 3.8.11 and later */
  sqlite3_value *(*value_dup)(const sqlite3_value*);
  void (*value_free)(sqlite3_value*);
  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  /* Version 3.9.0 and later */
  unsigned int (*value_subtype)(sqlite3_value*);
  void (*result_subtype)(sqlite3_context*,unsigned int);
  /* Version 3.10.0 and later */
  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  int (*strlike)(const char*,const char*,unsigned int);
  int (*db_cacheflush)(sqlite3*);
  /* Version 3.12.0 and later */
  int (*system_errno)(sqlite3*);
  /* Version 3.14.0 and later */
  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  char *(*expanded_sql)(sqlite3_stmt*);
  /* Version 3.18.0 and later */
  void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  /* Version 3.20.0 and later */
  int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
                    sqlite3_stmt**,const char**);
  int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
                      sqlite3_stmt**,const void**);
  int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
  void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
  void *(*value_pointer)(sqlite3_value*,const char*);
  int (*vtab_nochange)(sqlite3_context*);
  int (*value_nochange)(sqlite3_value*);
  const char *(*vtab_collation)(sqlite3_index_info*,int);
  /* Version 3.24.0 and later */
  int (*keyword_count)(void);
  int (*keyword_name)(int,const char**,int*);
  int (*keyword_check)(const char*,int);
  sqlite3_str *(*str_new)(sqlite3*);
  char *(*str_finish)(sqlite3_str*);
  void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
  void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
  void (*str_append)(sqlite3_str*, const char *zIn, int N);
  void (*str_appendall)(sqlite3_str*, const char *zIn);
  void (*str_appendchar)(sqlite3_str*, int N, char C);
  void (*str_reset)(sqlite3_str*);
  int (*str_errcode)(sqlite3_str*);
  int (*str_length)(sqlite3_str*);
  char *(*str_value)(sqlite3_str*);
  /* Version 3.25.0 and later */
  int (*create_window_function)(sqlite3*,const char*,int,int,void*,
                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
                            void (*xFinal)(sqlite3_context*),
                            void (*xValue)(sqlite3_context*),
                            void (*xInv)(sqlite3_context*,int,sqlite3_value**),
                            void(*xDestroy)(void*));
  /* Version 3.26.0 and later */
  const char *(*normalized_sql)(sqlite3_stmt*);
  /* Version 3.28.0 and later */
  int (*stmt_isexplain)(sqlite3_stmt*);
  int (*value_frombind)(sqlite3_value*);
  /* Version 3.30.0 and later */
  int (*drop_modules)(sqlite3*,const char**);
  /* Version 3.31.0 and later */
  sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);
  const char *(*uri_key)(const char*,int);
  const char *(*filename_database)(const char*);
  const char *(*filename_journal)(const char*);
  const char *(*filename_wal)(const char*);
  /* Version 3.32.0 and later */
  char *(*create_filename)(const char*,const char*,const char*,
                           int,const char**);
  void (*free_filename)(char*);
  sqlite3_file *(*database_file_object)(const char*);
  /* Version 3.34.0 and later */
  int (*txn_state)(sqlite3*,const char*);
};

/*
** This is the function signature used for all extension entry points.  It
** is also defined in the file "loadext.c".
*/
typedef int (*sqlite3_loadext_entry)(
  sqlite3 *db,                       /* Handle to the database. */
  char **pzErrMsg,                   /* Used to set error string on failure. */
  const sqlite3_api_routines *pThunk /* Extension API function pointers. */
);

/*
** The following macros redefine the API routines so that they are
** redirected through the global sqlite3_api structure.
**
** This header file is also used by the loadext.c source file
** (part of the main SQLite library - not an extension) so that
** it can get access to the sqlite3_api_routines structure
** definition.  But the main library does not want to redefine
** the API.  So the redefinition macros are only valid if the
** SQLITE_CORE macros is undefined.
*/
#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
#endif
#define sqlite3_bind_blob              sqlite3_api->bind_blob
#define sqlite3_bind_double            sqlite3_api->bind_double
#define sqlite3_bind_int               sqlite3_api->bind_int
#define sqlite3_bind_int64             sqlite3_api->bind_int64
#define sqlite3_bind_null              sqlite3_api->bind_null
#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
#define sqlite3_bind_text              sqlite3_api->bind_text
#define sqlite3_bind_text16            sqlite3_api->bind_text16
#define sqlite3_bind_value             sqlite3_api->bind_value
#define sqlite3_busy_handler           sqlite3_api->busy_handler
#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
#define sqlite3_changes                sqlite3_api->changes
#define sqlite3_close                  sqlite3_api->close
#define sqlite3_collation_needed       sqlite3_api->collation_needed
#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
#define sqlite3_column_blob            sqlite3_api->column_blob
#define sqlite3_column_bytes           sqlite3_api->column_bytes
#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
#define sqlite3_column_count           sqlite3_api->column_count
#define sqlite3_column_database_name   sqlite3_api->column_database_name
#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
#define sqlite3_column_decltype        sqlite3_api->column_decltype
#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
#define sqlite3_column_double          sqlite3_api->column_double
#define sqlite3_column_int             sqlite3_api->column_int
#define sqlite3_column_int64           sqlite3_api->column_int64
#define sqlite3_column_name            sqlite3_api->column_name
#define sqlite3_column_name16          sqlite3_api->column_name16
#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
#define sqlite3_column_table_name      sqlite3_api->column_table_name
#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
#define sqlite3_column_text            sqlite3_api->column_text
#define sqlite3_column_text16          sqlite3_api->column_text16
#define sqlite3_column_type            sqlite3_api->column_type
#define sqlite3_column_value           sqlite3_api->column_value
#define sqlite3_commit_hook            sqlite3_api->commit_hook
#define sqlite3_complete               sqlite3_api->complete
#define sqlite3_complete16             sqlite3_api->complete16
#define sqlite3_create_collation       sqlite3_api->create_collation
#define sqlite3_create_collation16     sqlite3_api->create_collation16
#define sqlite3_create_function        sqlite3_api->create_function
#define sqlite3_create_function16      sqlite3_api->create_function16
#define sqlite3_create_module          sqlite3_api->create_module
#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
#define sqlite3_data_count             sqlite3_api->data_count
#define sqlite3_db_handle              sqlite3_api->db_handle
#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
#define sqlite3_errcode                sqlite3_api->errcode
#define sqlite3_errmsg                 sqlite3_api->errmsg
#define sqlite3_errmsg16               sqlite3_api->errmsg16
#define sqlite3_exec                   sqlite3_api->exec
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_expired                sqlite3_api->expired
#endif
#define sqlite3_finalize               sqlite3_api->finalize
#define sqlite3_free                   sqlite3_api->free
#define sqlite3_free_table             sqlite3_api->free_table
#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
#define sqlite3_get_table              sqlite3_api->get_table
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_global_recover         sqlite3_api->global_recover
#endif
#define sqlite3_interrupt              sqlite3_api->interruptx
#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
#define sqlite3_libversion             sqlite3_api->libversion
#define sqlite3_libversion_number      sqlite3_api->libversion_number
#define sqlite3_malloc                 sqlite3_api->malloc
#define sqlite3_mprintf                sqlite3_api->mprintf
#define sqlite3_open                   sqlite3_api->open
#define sqlite3_open16                 sqlite3_api->open16
#define sqlite3_prepare                sqlite3_api->prepare
#define sqlite3_prepare16              sqlite3_api->prepare16
#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
#define sqlite3_profile                sqlite3_api->profile
#define sqlite3_progress_handler       sqlite3_api->progress_handler
#define sqlite3_realloc                sqlite3_api->realloc
#define sqlite3_reset                  sqlite3_api->reset
#define sqlite3_result_blob            sqlite3_api->result_blob
#define sqlite3_result_double          sqlite3_api->result_double
#define sqlite3_result_error           sqlite3_api->result_error
#define sqlite3_result_error16         sqlite3_api->result_error16
#define sqlite3_result_int             sqlite3_api->result_int
#define sqlite3_result_int64           sqlite3_api->result_int64
#define sqlite3_result_null            sqlite3_api->result_null
#define sqlite3_result_text            sqlite3_api->result_text
#define sqlite3_result_text16          sqlite3_api->result_text16
#define sqlite3_result_text16be        sqlite3_api->result_text16be
#define sqlite3_result_text16le        sqlite3_api->result_text16le
#define sqlite3_result_value           sqlite3_api->result_value
#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
#define sqlite3_snprintf               sqlite3_api->xsnprintf
#define sqlite3_step                   sqlite3_api->step
#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
#define sqlite3_total_changes          sqlite3_api->total_changes
#define sqlite3_trace                  sqlite3_api->trace
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
#endif
#define sqlite3_update_hook            sqlite3_api->update_hook
#define sqlite3_user_data              sqlite3_api->user_data
#define sqlite3_value_blob             sqlite3_api->value_blob
#define sqlite3_value_bytes            sqlite3_api->value_bytes
#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
#define sqlite3_value_double           sqlite3_api->value_double
#define sqlite3_value_int              sqlite3_api->value_int
#define sqlite3_value_int64            sqlite3_api->value_int64
#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
#define sqlite3_value_text             sqlite3_api->value_text
#define sqlite3_value_text16           sqlite3_api->value_text16
#define sqlite3_value_text16be         sqlite3_api->value_text16be
#define sqlite3_value_text16le         sqlite3_api->value_text16le
#define sqlite3_value_type             sqlite3_api->value_type
#define sqlite3_vmprintf               sqlite3_api->vmprintf
#define sqlite3_vsnprintf              sqlite3_api->xvsnprintf
#define sqlite3_overload_function      sqlite3_api->overload_function
#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
#define sqlite3_blob_close             sqlite3_api->blob_close
#define sqlite3_blob_open              sqlite3_api->blob_open
#define sqlite3_blob_read              sqlite3_api->blob_read
#define sqlite3_blob_write             sqlite3_api->blob_write
#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
#define sqlite3_file_control           sqlite3_api->file_control
#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
#define sqlite3_memory_used            sqlite3_api->memory_used
#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
#define sqlite3_mutex_free             sqlite3_api->mutex_free
#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
#define sqlite3_mutex_try              sqlite3_api->mutex_try
#define sqlite3_open_v2                sqlite3_api->open_v2
#define sqlite3_release_memory         sqlite3_api->release_memory
#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
#define sqlite3_sleep                  sqlite3_api->sleep
#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
#define sqlite3_vfs_find               sqlite3_api->vfs_find
#define sqlite3_vfs_register           sqlite3_api->vfs_register
#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
#define sqlite3_result_error_code      sqlite3_api->result_error_code
#define sqlite3_test_control           sqlite3_api->test_control
#define sqlite3_randomness             sqlite3_api->randomness
#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
#define sqlite3_limit                  sqlite3_api->limit
#define sqlite3_next_stmt              sqlite3_api->next_stmt
#define sqlite3_sql                    sqlite3_api->sql
#define sqlite3_status                 sqlite3_api->status
#define sqlite3_backup_finish          sqlite3_api->backup_finish
#define sqlite3_backup_init            sqlite3_api->backup_init
#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
#define sqlite3_backup_step            sqlite3_api->backup_step
#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
#define sqlite3_db_config              sqlite3_api->db_config
#define sqlite3_db_mutex               sqlite3_api->db_mutex
#define sqlite3_db_status              sqlite3_api->db_status
#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
#define sqlite3_log                    sqlite3_api->log
#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
#define sqlite3_sourceid               sqlite3_api->sourceid
#define sqlite3_stmt_status            sqlite3_api->stmt_status
#define sqlite3_strnicmp               sqlite3_api->strnicmp
#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
#define sqlite3_wal_hook               sqlite3_api->wal_hook
#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
#define sqlite3_vtab_config            sqlite3_api->vtab_config
#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
/* Version 3.7.16 and later */
#define sqlite3_close_v2               sqlite3_api->close_v2
#define sqlite3_db_filename            sqlite3_api->db_filename
#define sqlite3_db_readonly            sqlite3_api->db_readonly
#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
#define sqlite3_errstr                 sqlite3_api->errstr
#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
#define sqlite3_stricmp                sqlite3_api->stricmp
#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
#define sqlite3_uri_int64              sqlite3_api->uri_int64
#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
#define sqlite3_uri_vsnprintf          sqlite3_api->xvsnprintf
#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
/* Version 3.8.7 and later */
#define sqlite3_auto_extension         sqlite3_api->auto_extension
#define sqlite3_bind_blob64            sqlite3_api->bind_blob64
#define sqlite3_bind_text64            sqlite3_api->bind_text64
#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
#define sqlite3_load_extension         sqlite3_api->load_extension
#define sqlite3_malloc64               sqlite3_api->malloc64
#define sqlite3_msize                  sqlite3_api->msize
#define sqlite3_realloc64              sqlite3_api->realloc64
#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
#define sqlite3_result_blob64          sqlite3_api->result_blob64
#define sqlite3_result_text64          sqlite3_api->result_text64
#define sqlite3_strglob                sqlite3_api->strglob
/* Version 3.8.11 and later */
#define sqlite3_value_dup              sqlite3_api->value_dup
#define sqlite3_value_free             sqlite3_api->value_free
#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
/* Version 3.9.0 and later */
#define sqlite3_value_subtype          sqlite3_api->value_subtype
#define sqlite3_result_subtype         sqlite3_api->result_subtype
/* Version 3.10.0 and later */
#define sqlite3_status64               sqlite3_api->status64
#define sqlite3_strlike                sqlite3_api->strlike
#define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
/* Version 3.12.0 and later */
#define sqlite3_system_errno           sqlite3_api->system_errno
/* Version 3.14.0 and later */
#define sqlite3_trace_v2               sqlite3_api->trace_v2
#define sqlite3_expanded_sql           sqlite3_api->expanded_sql
/* Version 3.18.0 and later */
#define sqlite3_set_last_insert_rowid  sqlite3_api->set_last_insert_rowid
/* Version 3.20.0 and later */
#define sqlite3_prepare_v3             sqlite3_api->prepare_v3
#define sqlite3_prepare16_v3           sqlite3_api->prepare16_v3
#define sqlite3_bind_pointer           sqlite3_api->bind_pointer
#define sqlite3_result_pointer         sqlite3_api->result_pointer
#define sqlite3_value_pointer          sqlite3_api->value_pointer
/* Version 3.22.0 and later */
#define sqlite3_vtab_nochange          sqlite3_api->vtab_nochange
#define sqlite3_value_nochange         sqlite3_api->value_nochange
#define sqlite3_vtab_collation         sqlite3_api->vtab_collation
/* Version 3.24.0 and later */
#define sqlite3_keyword_count          sqlite3_api->keyword_count
#define sqlite3_keyword_name           sqlite3_api->keyword_name
#define sqlite3_keyword_check          sqlite3_api->keyword_check
#define sqlite3_str_new                sqlite3_api->str_new
#define sqlite3_str_finish             sqlite3_api->str_finish
#define sqlite3_str_appendf            sqlite3_api->str_appendf
#define sqlite3_str_vappendf           sqlite3_api->str_vappendf
#define sqlite3_str_append             sqlite3_api->str_append
#define sqlite3_str_appendall          sqlite3_api->str_appendall
#define sqlite3_str_appendchar         sqlite3_api->str_appendchar
#define sqlite3_str_reset              sqlite3_api->str_reset
#define sqlite3_str_errcode            sqlite3_api->str_errcode
#define sqlite3_str_length             sqlite3_api->str_length
#define sqlite3_str_value              sqlite3_api->str_value
/* Version 3.25.0 and later */
#define sqlite3_create_window_function sqlite3_api->create_window_function
/* Version 3.26.0 and later */
#define sqlite3_normalized_sql         sqlite3_api->normalized_sql
/* Version 3.28.0 and later */
#define sqlite3_stmt_isexplain         sqlite3_api->stmt_isexplain
#define sqlite3_value_frombind         sqlite3_api->value_frombind
/* Version 3.30.0 and later */
#define sqlite3_drop_modules           sqlite3_api->drop_modules
/* Version 3.31.0 and later */
#define sqlite3_hard_heap_limit64      sqlite3_api->hard_heap_limit64
#define sqlite3_uri_key                sqlite3_api->uri_key
#define sqlite3_filename_database      sqlite3_api->filename_database
#define sqlite3_filename_journal       sqlite3_api->filename_journal
#define sqlite3_filename_wal           sqlite3_api->filename_wal
/* Version 3.32.0 and later */
#define sqlite3_create_filename        sqlite3_api->create_filename
#define sqlite3_free_filename          sqlite3_api->free_filename
#define sqlite3_database_file_object   sqlite3_api->database_file_object
/* Version 3.34.0 and later */
#define sqlite3_txn_state              sqlite3_api->txn_state
#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */

#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  /* This case when the file really is being compiled as a loadable 
  ** extension */
# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
# define SQLITE_EXTENSION_INIT3     \
    extern const sqlite3_api_routines *sqlite3_api;
#else
  /* This case when the file is being statically linked into the 
  ** application */
# define SQLITE_EXTENSION_INIT1     /*no-op*/
# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
# define SQLITE_EXTENSION_INIT3     /*no-op*/
#endif

#endif /* SQLITE3EXT_H */

Deleted subdir-inc.make.

1
2
3
4
5
6
7







-
-
-
-
-
-
-
#!/do/not/make # to help out emacs
# To be included from subdir GNU Makefiles.
TOP_DIR := $(patsubst %/,%,$(dir $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))))
#$(error TOP_DIR=$(TOP_DIR))
include $(TOP_DIR)/config.make
include $(TOP_DIR)/shakenmake.make