aboutsummaryrefslogtreecommitdiff
path: root/ttt.jai
blob: e24419d3b9b00f911847c16ecfa353a5424eae67 (plain)
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
// Copyright 2023 Daniel Martins
// License GPL-3.0-or-later
//
// This program 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/>. 

// Compilation commands:
// - release                : jai ttt.jai -import_dir . -x64 -release
// - debug                  : jai ttt.jai -import_dir . -x64

#import "Basic";
#import "System";
#import "Math";
#import "POSIX";
#import "File";
#import "String";
#import "curses";


VERSION             :: "2.0";   // Use only 3 chars (to fit layouts).
YEAR                :: "2023";
TASK_NAME_LENGTH    :: 57;
TASK_NAME_BYTES     :: #run TASK_NAME_LENGTH+1; // TODO Get rid of this!
FIRST_DAY_OF_WEEK   :: 1;       // (0-6, Sunday = 0).
NUM_WEEK_DAYS       :: 7;       // Just to be more clear about what we're looping about.

APP_FOLDER_NAME     :: ".task_time_tracker_v2"; // TODO Using _v2 to avoid erasing my work data.
DB_FILE_NAME        :: "database.bin";
AR_FILE_NAME        :: "archive.csv";

DB_FILE_SIGN_STR    :: "TTT:B:02";
SECONDS_IN_MINUTE   :: cast(s64)60;
SECONDS_IN_HOUR     :: cast(s64)60*SECONDS_IN_MINUTE;
SECONDS_IN_DAY      :: cast(s64)24*SECONDS_IN_HOUR;
SECONDS_IN_YEAR     :: cast(s64)365*SECONDS_IN_DAY;
MAX_DATABASE_TASKS  :: S64_MAX;

Task :: struct {
    times       : [NUM_WEEK_DAYS] s64;
    name        : [72] u8;
    //name_data   : [70] u8;
    //name.data   = cast(*~s8 u8) (0x80 ^ 0x01); // *name_data[0];
}

Database :: struct {
    modified_on     : Apollo_Time;
    active_idx      : s64;
    selected_idx    : s64;
    total_times     : [NUM_WEEK_DAYS] s64;
    tasks           : [..] Task;
}

// const char DB_FILE_SIGN[]           = DB_FILE_SIGN_STR;
// const size_t DB_FILE_SIGN_LENGTH    = sizeof(DB_FILE_SIGN_STR)-1;
// const size_t SIZEOF_TASK_ST         = sizeof(task_st);
// const size_t SIZEOF_DATABASE_ST     = sizeof(database_st);
// const size_t SIZEOF_CHAR            = sizeof(char);
// const size_t SIZEOF_INT64           = sizeof(int64_t);
// 
// 
// 
// database_st database        = { .tasks = NULL };
// database_st archive         = { .tasks = NULL };
// database_st *db             = NULL;
is_autosave_enabled     := true;
// int countdown_to_autosave   = -1;
app_directory           : string;
db_file_path            : string;
ar_file_path            : string;
// char *string_buffer         = NULL; // A temporary buffer for localized actions. Please avoid data leaks and out-of-bounds errors.
// size_t string_buffer_size   = 0;
// int size_x, size_y, pos_x, pos_y;

// typedef enum {
//     STYLE_SELECTED = 1,
//     STYLE_SELECTED_INVERTED,
//     STYLE_ACTIVE,
//     STYLE_ACTIVE_SELECTED,
//     STYLE_ERROR,
// } styles_et;

error_window        : *WINDOW = null;
error_time_limit    := Apollo_Time.{0, 0};

print_error :: (format :string, args : .. Any) {
    // NOTE Implement me please.
//     if stdscr == null || isendwin() == true { // Not in ncurses mode?
        print(format, ..args);
        print("\n");
//     }
//     else {
//         int w_size_x = size_x > 120 ? 120 : size_x - 2;
//         int w_size_y = 4;
//         if (error_window == NULL) {
//             error_window = newwin(w_size_y, w_size_x, (size_y - w_size_y) / 2, (size_x - w_size_x) / 2);
//             wattron(error_window, COLOR_PAIR(STYLE_ERROR));
//             wborder(error_window, ' ', ' ', 0, 0, ACS_HLINE, ACS_HLINE, ACS_HLINE, ACS_HLINE);
//             mvwprintw(error_window, 0, 1, " Error ");
//             wmove(error_window, 1, 0);
//         }
//         else {
//             waddch(error_window, ' ');
//         }
//         vw_printw(error_window, format, args);
//         error_time_limit = time(NULL) + 5; // NOTE Instead of time use the current_time_monotonic()
//     }
}

draw_error_window :: () {
    /* NOTE Implement me please.
    if (error_window == NULL) {
        return;
    }
    
    // Hide error window after time-limit or if terminal is shrank.
    int w_size_x, w_size_y;
    getmaxyx(error_window, w_size_y, w_size_x);
    if (time(NULL) >= error_time_limit
        || size_x - w_size_x < 2
        || size_y - w_size_y < 2
    ) {
        delwin(error_window);
        error_window = NULL;
        return;
    }
    
    // Adjust error window position.
    int pos_x = (size_x - w_size_x) / 2;
    int pos_y = (size_y - w_size_y) / 2;
    mvwin(error_window, pos_y, pos_x);
    
    // Avoid being overwritten by main window content.
    refresh();
    touchwin(error_window);
    wrefresh(error_window);
    */
}

/*
void trigger_autosave() {
    countdown_to_autosave = 13375; // ms
}

void show_processing() {
    mvaddch(0, 0, ACS_DIAMOND);
    refresh();
}

// Checks if file is exists and is accessible.
// Returns true when the file exists and is accessible.
bool is_file_accessible(const char *path) {
    assert(path != NULL);
    FILE *file = fopen(path, "r+");
    bool is_file_accessible = file != NULL;
    if (is_file_accessible) {
        fclose(file);
    }
    return is_file_accessible;
}
*/

// Returns true if string to_compare is equal to any of the other passed strings, false otherwise.
is_equal_to_any :: (to_compare :string, test_a :string, test_b :string) -> bool {
    return to_compare == test_a || to_compare == test_b;
}

// Given an UTF8 encoded string, truncate it to length bytes without breaking any UTF8 character.
// The string should have capacity for at least length + 1.
// The terminating null byte ('\0') is not included in length.
// Returns the truncated string length.
truncate_string_utf8 :: (str: string, length: s64) -> length: s64 {
    assert(str.data != null);
    assert(str.count >= length);

    data := str.data;
    count := str.count;
    
    // Find index of first continuation byte.
    idx := length;
    while (idx > 0 && ((data[idx - 1] & 0xC0) == 0x80)) {
        idx -= 1;
    }
    continuation_bytes := length - idx;
    
    // If string starts with continuation bytes, it's an invalid UTF8 string.
    if (idx == 0 && continuation_bytes > 0) {
        length = 0;
    }
    // If length truncates some continuation bytes, remove incomplete UTF8 character.
    else if (idx > 0 // string is not empty
        // continuation bytes are not complete
        && !(continuation_bytes == 0 && (data[idx - 1] & 0x80) == 0x00)
        && !(continuation_bytes == 1 && (data[idx - 1] & 0xE0) == 0xC0)
        && !(continuation_bytes == 2 && (data[idx - 1] & 0xF0) == 0xE0)
        && !(continuation_bytes == 3 && (data[idx - 1] & 0xF8) == 0xF0)
    ) {
        length -= (continuation_bytes + 1); // Remove '+ 1' start byte.
    }

    ptr := data + length;
    memset(ptr, 0, str.count - length);
    return length;
}
/*
// Returns true when the string is empty or consists of white space characters.
bool is_empty_string(const char *string) {
    for (int idx = 0; string[idx] != '\0'; idx++) {
        switch(string[idx]) {
            case ' ':
            case '\t':
            case '\v':
            case '\f':
            case '\r':
            case '\n':
                break;
            default:
                return false;
        }
    }
    return true;
}

// Uses strchr to replace all instances of find by replace.
// Returns string.
char *replace_char(char *string, char find, char replace) {
    char *idx = string;
    while((idx = strchr(idx, find)) != NULL) {
        *idx = replace;
        idx++;
    }
    return string;
}

// Prints, on row y and column x, the time using 5 characters centered on space.
// Returns the result of a call to mvprintw.
int mvprintw_time(int y, int x, intmax_t time, int space) {
    const int TIME_CHARS = 5;
    assert(space >= TIME_CHARS);
    
    int left_padding = (space - TIME_CHARS) / 2;
    int right_padding = space - TIME_CHARS - left_padding;
    
    if (time < 0) {
        return mvprintw(y, x, "%*s  -  %*s", left_padding, "", right_padding, "");
    }
    else if (time == 0) {
        return mvprintw(y, x, "%*s  0  %*s", left_padding, "", right_padding, "");
    }
    else if (time < SECONDS_IN_MINUTE) {
        return mvprintw(y, x, "%*s%3jds %*s", left_padding, "", time, right_padding, "");
    }
    else if (time < (intmax_t)100 * SECONDS_IN_HOUR) {
        intmax_t hours = (double)time / (double)SECONDS_IN_HOUR;
        intmax_t minutes = (time - (hours * SECONDS_IN_HOUR) ) / SECONDS_IN_MINUTE;
        return mvprintw(y, x, "%*s%02jd:%02jd%*s", left_padding, "", hours, minutes, right_padding, "");
    }
    else if (time < (intmax_t)(9999.5 * SECONDS_IN_DAY)) {
        double value = (double)time / (double)SECONDS_IN_DAY;
        int decimals =
            time >= 99.95 * SECONDS_IN_DAY ? 0 :
            time >= 9.995 * SECONDS_IN_DAY ? 1 :
            2;
        return mvprintw(y, x, "%*s%4.*fd%*s", left_padding, "", decimals, value, right_padding, "");
    }
    else if (time < (intmax_t)(9999.5 * SECONDS_IN_YEAR)) {
        double value = (double)time / (double)SECONDS_IN_YEAR;
        int decimals =
            time >= 99.95 * SECONDS_IN_YEAR ? 0 :
            time >= 9.995 * SECONDS_IN_YEAR ? 1 :
            2;
        return mvprintw(y, x, "%*s%4.*fy%*s", left_padding, "", decimals, value, right_padding, "");
    }
    else {
        return mvprintw(y, x, "%*s  ∞  %*s", left_padding, "", right_padding, "");
    }
}
*/

add_int64 :: (x :s64, y: s64) -> s64 {
    return
        ifx (y > 0 && x > S64_MAX - y) then S64_MAX else
        ifx (y < 0 && x < S64_MIN - y) then S64_MIN else
        x + y;
}

sub_int64 :: (x :s64, y :s64) -> s64 {
    return
        ifx (y < 0 && x > S64_MAX + y) then S64_MAX else
        ifx (y > 0 && x < S64_MIN + y) then S64_MIN else
        x - y;
}

/*
// Returns active task or NULL if none applies.
task_st *get_active_task(database_st *db) {
    assert(db != NULL);
    
    task_st *task = NULL;
    if (db->active_task >= 0) {
        task = db->tasks + db->active_task;
    }
    return task;
}

// Returns selected task or NULL if none applies.
task_st *get_selected_task(database_st *db) {
    assert(db != NULL);
    
    task_st *task = NULL;
    if (db->selected_task >= 0) {
        task = db->tasks + db->selected_task;
    }
    return task;
}
*/
// Creates new task stored at location given by task pointer.
// If necessary, expands database capacity.
// Returns success.
add_task :: (db: *Database, task: *Task) -> success: bool {
    idx := db.tasks.count;
    maybe_grow(*db.tasks); // TODO Check for errors?
    db.tasks.count += 1;
    db.tasks[idx] = task;
    return true;
}
/*
// Creates new task stored at location given by task pointer.
// If necessary, expands database capacity.
// Returns success.
bool create_task(database_st *db, task_st **task) {
    assert(db != NULL);
    assert(task != NULL);
    
    if (db->count >= MAX_DATABASE_TASKS) {
        print_error("Database reached maximum capacity.");
        return false;
    }
    
    // If necessary, expand database capacity.
    size_t current_capacity = db->capacity;
    if ((db->count + 1) > current_capacity) {
        size_t new_capacity =
            current_capacity == 0 ? 2 :
            current_capacity > (MAX_DATABASE_TASKS >> 1) ? MAX_DATABASE_TASKS :
            current_capacity << 1;
        
        task_st *new_tasks = realloc(db->tasks, new_capacity * SIZEOF_TASK_ST);
        if (new_tasks == NULL) {
            print_error("Failed to expand database.");
            return false;
        }
        
        db->capacity = new_capacity;
        db->tasks = new_tasks;
    }
    
    // Prepare new task.
    *task = &db->tasks[db->count];
    memset(*task, 0, SIZEOF_TASK_ST);
    
    db->count++;
    
    // Adjust selected task.
    if (db->selected_task < 0) {
        db->selected_task = db->count-1;
    }
    
    return true;
}

// Duplicates the given task. Duplicated task is appended to the database.
// Returns success.
bool duplicate_task(database_st *db, task_st *task) {
    assert(db != NULL);
    assert(task != NULL);
    
    // Create new task and keep task_idx (relative pointer) of original task).
    ptrdiff_t task_idx = task - db->tasks;
    task_st *new_task;
    if (create_task(db, &new_task) == false) {
        return false;
    }
    
    // If original task belonged to database, fix its pointer.
    if (0 <= task_idx && task_idx < db->count - 1) { // Compensate '- 1' for the new task.
        task = db->tasks + task_idx;
    }
    
    memcpy(new_task, task, SIZEOF_TASK_ST);
    
    // Add task time values to total times.
    for (int idx = 0; idx < NUM_WEEK_DAYS; idx++) {
        db->total_times[idx] = add_int64(db->total_times[idx], new_task->times[idx]);
    }
    
    return true;
}

// Deletes task from database.
// If possible, shrinks the database capacity.
// Returns success.
bool delete_task(database_st *db, task_st *task) {
    assert(db != NULL);
    assert(task != NULL);
    assert(task >= db->tasks && task - db->tasks < db->count);
    
    // Remove task timer values from total timers.
    for (int idx = 0; idx < NUM_WEEK_DAYS; idx++) {
        db->total_times[idx] = sub_int64(db->total_times[idx], task->times[idx]);
    }
    
    // Move tasks after the index position to their new positions.
    ptrdiff_t index = task - db->tasks;
    memmove(task, task + 1, (db->count - index - 1) * SIZEOF_TASK_ST);
    db->count--;
    
    // Adjust selected task.
    if (db->selected_task >= db->count) {
        db->selected_task--;
    }
    
    // Adjust active task.
    if (db->active_task > index) {
        db->active_task--;
    }
    else if (db->active_task == index) {
        db->active_task = -1;
    }
    
    // If possible, shrink database capacity.
    size_t current_capacity = db->capacity;
    if (db->count <= (current_capacity >> 2)) {
        size_t new_capacity = current_capacity >> 1;
        task_st *new_tasks = realloc(db->tasks, new_capacity * SIZEOF_TASK_ST);
        if (new_tasks == NULL && new_capacity > 0) {
            print_error("Failed to shrink database.");
            return false;
        }
        db->capacity = new_capacity;
        db->tasks = new_tasks;
    }
    
    return true;
}

// Moves task to index.
// Index gets clamped to [0, db->count[.
void move_task_to_index(database_st *db, task_st *task, ptrdiff_t index) {
    assert(db != NULL);
    assert(task != NULL);
    assert(task >= db->tasks && task - db->tasks < db->count);
    
    ptrdiff_t target_index = index < 0 ? 0
        : index >= db->count ? db->count - 1
        : index;
    
    task_st *target_task = db->tasks + target_index;
    
    if (target_task == task) {
        return;
    }
    
    // Move task to new location.
    task_st temp_task;
    memcpy(&temp_task, task, SIZEOF_TASK_ST);
    if (target_task > task) {
        memmove(task, task + 1, (target_task - task) * SIZEOF_TASK_ST);
    }
    else {
        memmove(target_task + 1, target_task, (task - target_task) * SIZEOF_TASK_ST);
    }
    memcpy(target_task, &temp_task, SIZEOF_TASK_ST);
    
    // Adjust active and selected tasks.
    ptrdiff_t source_index = task - db->tasks;
    if (db->active_task == source_index) {
        db->active_task = target_index;
    }
    else if (source_index < db->active_task && db->active_task <= target_index) {
        db->active_task--;
    }
    else if (target_index <= db->active_task && db->active_task < source_index) {
        db->active_task++;
    }
    db->selected_task = target_index;
}

// Updates the times on the active task (and adjusts database totals).
void update_times(database_st *db) {
    assert(db != NULL);
    
    // Get current UTC time.
    time_t stop_time = time(NULL);
    
    // Get last modified on UTC time.
    time_t start_time = db->modified_on;
    
    // Keep track of this update.
    db->modified_on = stop_time;
    
    if (db->active_task < 0) {
        return;
    }
    
    task_st *active_task = db->tasks + db->active_task;
    uint8_t start_week_day;
    while (start_time < stop_time) {
        
        start_week_day = localtime(&start_time)->tm_wday;
        
        // Get next day in local time.
        struct tm *start_of_day_tm = localtime(&start_time);
        start_of_day_tm->tm_sec = 0;
        start_of_day_tm->tm_min = 0;
        start_of_day_tm->tm_hour = 0;
        time_t start_of_day = mktime(start_of_day_tm);
        time_t next_day = start_of_day + SECONDS_IN_DAY;
        time_t next_start = next_day < stop_time ? next_day : stop_time;
        time_t elapsed_time = next_start - start_time;
        active_task->times[start_week_day] += elapsed_time;
        db->total_times[start_week_day] += elapsed_time;
        
        start_time = next_start;
    }
}

// Recalculates database totals.
void update_total_times(database_st *db) {
    assert(db != NULL);
    
    int64_t *totals = db->total_times;
    memset(totals, 0, NUM_WEEK_DAYS * SIZEOF_INT64);
    for (size_t idx = 0; idx < db->count; idx++) {
        int64_t *times = db->tasks[idx].times;
        totals[0] = add_int64(totals[0], times[0]);
        totals[1] = add_int64(totals[1], times[1]);
        totals[2] = add_int64(totals[2], times[2]);
        totals[3] = add_int64(totals[3], times[3]);
        totals[4] = add_int64(totals[4], times[4]);
        totals[5] = add_int64(totals[5], times[5]);
        totals[6] = add_int64(totals[6], times[6]);
    }
}

// Resets the times of the provided task (and adjusts database totals).
void reset_task_times(database_st *db, task_st *task) {
    assert(db != NULL);
    assert(task != NULL);
    assert(task >= db->tasks && task - db->tasks < db->count);
    
    // Make sure we sync before applying the changes.
    update_times(db);
    
    for (int idx = 0; idx < NUM_WEEK_DAYS; idx++) {
        int64_t *timer = &task->times[idx];
        int64_t *total = &db->total_times[idx];
        *total = sub_int64(*total, *timer);
        *timer = 0;
    }
}

// Sets the time on the day and task provided (and adjusts database totals).
void set_task_time(database_st *db, task_st *task, int day, int64_t time) {
    assert(db != NULL);
    assert(task != NULL);
    assert(task >= db->tasks && task - db->tasks < db->count);
    
    // Make sure we sync before applying the changes.
    update_times(db);
    
    int64_t *timer = &task->times[day];
    int64_t *total = &db->total_times[day];
    *total = sub_int64(*total, *timer);
    *timer = time;
    *total = add_int64(*total, *timer);
}

// Adds the time on the day and task provided (and adjusts database totals).
void add_task_time(database_st *db, task_st *task, int day, int64_t time) {
    assert(db != NULL);
    assert(task != NULL);
    assert(task >= db->tasks && task - db->tasks < db->count);
    
    // Make sure we sync before applying the changes.
    update_times(db);
    
    task->times[day] = add_int64(task->times[day], time);
    db->total_times[day] = add_int64(db->total_times[day], time);
}

// Resets database to the initial state and deallocates all memory taken by tasks.
void reset_database(database_st *db) {
    assert(db != NULL);
    
    free(db->tasks);
    memset(db, 0, SIZEOF_DATABASE_ST);
    db->active_task = -1;
    db->selected_task = -1;
}

// Stores data from database into binary file.
// Returns success.
bool store_database(const database_st *db, const char *path) {
    assert(db != NULL);
    assert(path != NULL);
    
    // Open file.
    FILE *file = fopen(path, "wb");
    if (file == NULL) {
        print_error("Failed to open file '%s' while storing database: %s.", path, strerror(errno));
        return false;
    }
    
    fwrite(DB_FILE_SIGN, SIZEOF_CHAR, DB_FILE_SIGN_LENGTH, file);
    fwrite(db, SIZEOF_DATABASE_ST, 1, file);
    fwrite(db->tasks, SIZEOF_TASK_ST, db->count, file);
    
    fclose(file);
    return true;
}

// Loads data from binary file into database.
// Returns success.
bool load_database(database_st *db, const char *path) {
    assert(db != NULL);
    assert(path != NULL);
    
    // Open file.
    FILE *file = fopen(path, "rb");
    if (file == NULL) {
        print_error("Failed to open file '%s' while loading database: %s.", path, strerror(errno));
        return false;
    }
    
    // Validate file signature.
    char file_signature[DB_FILE_SIGN_LENGTH];
    fread(&file_signature, SIZEOF_CHAR, DB_FILE_SIGN_LENGTH, file);
    if (strncmp(file_signature, DB_FILE_SIGN, DB_FILE_SIGN_LENGTH) != 0) {
        print_error("Invalid file signature.");
        fclose(file);
        return false;
    }
    
    // Read database structure.
    fread(db, SIZEOF_DATABASE_ST, 1, file);
    
    // Reserve database capacity for tasks.
    size_t capacity_bytes = db->capacity * SIZEOF_TASK_ST;
    db->tasks = malloc(capacity_bytes);
    if (db->tasks == NULL && capacity_bytes > 0) {
        print_error("Failed to allocate memory while loading database: %s.", strerror(errno));
        return false;
    }
    
    // Read database tasks.
    fread(db->tasks, SIZEOF_TASK_ST, db->count, file);
    
    // Make sure we are reading all the file.
    assert(fgetc(file) == EOF);
    
    fclose(file);
    return true;
}

// Exports data into CSV file.
// Returns success.
bool export_to_csv(const database_st *db, const char *path) {
    assert(db != NULL);
    assert(path != NULL);
    
    FILE *file = fopen(path, "w");
    if (file == NULL) {
        print_error("Failed to open file '%s' while exporting to CSV: %s.", path, strerror(errno));
        return false;
    }
    
    fprintf(file, "%s,%s,%s,%s,%s,%s,%s,%s\n",
        "task", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"
    );
    
    char name[TASK_NAME_BYTES];
    for (size_t idx = 0; idx < db->count; idx++) {
        task_st *task = &db->tasks[idx];
        memcpy(name, task->name, TASK_NAME_BYTES);
        replace_char(name, ',', ' ');
        fprintf(file, "%s,%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64 "\n",
            name, task->times[0], task->times[1], task->times[2], task->times[3], task->times[4], task->times[5], task->times[6]
        );
    }
    
    fclose(file);
    return true;
}
*/
// Imports CSV file into database.
// Returns success.
import_from_csv :: (db: *Database, path: string) -> bool {
    
    // TODO WIP
    
    assert(db != null, "Parameter 'db' is null.");
    assert(xx path, "Parameter 'path' is empty.");
    error_code: s64;
    
    // Check file size
    file_info: stat_t;
    error_code = sys_stat(path, *file_info); // TODO Check for error.
    size := file_info.st_size;
    
    success: bool;
    map: Map_File_Info;
    data: string;
    is_using_map := false;
    if size >= 1<<30 {
        print("big file with % MB\n", size>>20); // TODO
        map, success = map_entire_file_start(path);
        data = map.data;
        is_using_map = true;
    }
    else {
        print("small file with % B\n", size); // TODO
        data, success = read_entire_file(path);
    }
    defer if is_using_map then map_entire_file_end(*map); else free(data.data);
    csv := data;
    
    if success == false {
        print_error("Failed to read file '%' while loading database: ERROR_FROM_LOG", path); // TODO Get error from logger ?!
        return false;
    }
    
    // TODO Helper function.
    consume_next_line :: (sp: *string) -> string, bool {
        // To find the end of the line, we look for a linefeed character.
        // We will trim a carriage return off the end if there is one there also.
        // Thus this works on both 'dos' and 'unix'-style files.

        s := << sp;
        found, result, right := split_from_left(s, 10);

        if !found {
            // This is the last line; there may not have been a linefeed after that,
            // but we still want to handle that data, so we return true if there was
            // a nonzero amount of stuff there.
            
            << sp = "";

            return s, (s.count > 0);
        }

        // Chop the characters we are going to return from 'sp',
        // which holds the remaining file data.
        advance(sp, result.count + 1);

        if result {
            if result[result.count-1] == 13  result.count -= 1;  // If there's a carriage return at the end, remove it by decrementing the string's length.
        }
        
        return result, true;
    }
    
    //Skip header line.
    consume_next_line(*csv);
    
    // TODO Helper function.
    advance :: inline (array: *[] $T, amount: int = 1) {
        assert(amount >= 0);
        assert(array.count >= amount);
        array.count -= amount;
        array.data  += amount;
    }
    
    next_line :: inline (csv: *string) -> line: string, success: bool {
        for 0..csv.count {
            if csv.data[it] == #char "\n" {
                line: string = <<csv;
                line.count = it;
                csv.data += it + 1;
                csv.count -= it + 1;
                return line, true;
            }
        }
        return "", false;
    }
    
    // Parse CSV lines.
    line := csv;
    while (true) {
        line, success := consume_next_line(*csv);
//         line, success := next_line(*csv);
        if success == false break;
        
        task: Task;
        values := split(line, ","); // TODO Temporary memory... if file is too big this may break.
        memcpy(task.name.data, values[0].data, xx min(task.name.count, values[0].count));
        advance(*values);
        for values {
            task.times[it_index] = string_to_int(it);
        }
        
        add_task(db, *task);
//         if context.temporary_storage.total_bytes_occupied > (100<<20) {
//             print("temp: %\n", context.temporary_storage.total_bytes_occupied >> 20);
//             reset_temporary_storage();
//         }
    }
    print("temp: %\n", context.temporary_storage.total_bytes_occupied >> 20);
    reset_temporary_storage();

    return false;
}
/*
// Appends task to the end of the CSV file.
// Returns success.
bool append_to_csv(task_st *task, const char *path) {
    assert(task != NULL);
    assert(path != NULL);
    
    FILE *file = fopen(path, "a+");
    if (file == NULL) {
        print_error("Failed to open file '%s' while appending to CSV: %s.", path, strerror(errno));
        return false;
    }
    
    char last_char;
    fseek(file, -1, SEEK_END);
    fread(&last_char, SIZEOF_CHAR, 1, file);
    if (last_char != '\n') {
        fprintf(file, "\n");
    }
    
    char name[TASK_NAME_BYTES];
    memcpy(name, task->name, TASK_NAME_BYTES);
    replace_char(name, ',', ' ');
    fprintf(file, "%s,%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64 "\n",
        name, task->times[0], task->times[1], task->times[2], task->times[3], task->times[4], task->times[5], task->times[6]
    );
    
    fclose(file);
    return true;
}

// Selects task by index.
// Index gets clamped to [0, db->count[.
void select_task_by_index(database_st *db, ptrdiff_t index) {
    assert(db != NULL);
    db->selected_task = db->count == 0 ? -1
        : index < 0 ? 0
        : index >= db->count ? db->count - 1
        : index;
}

// Selects task by delta relative to currently selected task.
void select_task_by_delta(database_st *db, ptrdiff_t delta) {
    assert(db != NULL);
    ptrdiff_t idx = (delta > 0 && db->selected_task > PTRDIFF_MAX - delta) ? PTRDIFF_MAX
        : (delta < 0 && db->selected_task < PTRDIFF_MIN + delta) ? PTRDIFF_MIN
        : db->selected_task + delta;
    select_task_by_index(db, idx);
}

// Selects task.
void select_task(database_st *db, task_st *task) {
    assert(db != NULL);
    assert(task != NULL);
    assert(task >= db->tasks && task - db->tasks < db->count);
    db->selected_task = task - db->tasks;
}

// Set active task.
// Passing task as NULL de-activates any previously active task.
void set_active_task(database_st *db, task_st *task) {
    assert(db != NULL);
    assert(task == NULL || (task >= db->tasks && task < &db->tasks[db->count]));
    update_times(db);
    db->active_task = (task == NULL) ? -1 : task - db->tasks;
}

// Returns true when database is full.
bool is_database_full(database_st *db) {
    assert(db != NULL);
    return db->count >= MAX_DATABASE_TASKS;
}

#define INPUT_TIMEOUT_MS    1000
#define INPUT_AWAIT_INF     -1

#define NUM_HEADER_ROWS     1
#define NUM_FOOTER_ROWS     1
#define NUM_COLUMNS         9

#define L_TITLE_IDX         0
#define L_DAYS_IDX          1
#define L_TOTAL_IDX         8

typedef enum {
    L_NORMAL,
    L_COMPACT,
    NUM_LAYOUTS,
} layouts_et;

typedef struct {
    char        *header;
    int         width;
    int         alignment_offset;
    char        alignment;
} column_st;

typedef struct {
    column_st   columns[NUM_COLUMNS];
    char        *archive_title;
} layout_st;

layout_st   layouts[NUM_LAYOUTS];
int         layout_tasks_rows;
bool        is_terminal_too_small = true;


void initialize_tui() {
    
    // Normal layout.
    layouts[L_NORMAL] = (layout_st) {
        .archive_title = " Archive ",
        .columns = {
            {   .header = " Task Time Tracker v" VERSION " ", .width = -1, .alignment = 'L' },
            {   .header = " Sun ",      .width = 7,     .alignment = 'C'    },
            {   .header = " Mon ",      .width = 7,     .alignment = 'C'    },
            {   .header = " Tue ",      .width = 7,     .alignment = 'C'    },
            {   .header = " Wed ",      .width = 7,     .alignment = 'C'    },
            {   .header = " Thu ",      .width = 7,     .alignment = 'C'    },
            {   .header = " Fri ",      .width = 7,     .alignment = 'C'    },
            {   .header = " Sat ",      .width = 7,     .alignment = 'C'    },
            {   .header = " Total ",    .width = 9,     .alignment = 'C'    },
        }
    };
    
    // Compact layout.
    layouts[L_COMPACT] = (layout_st) {
        .archive_title = " Archive ",
        .columns = {
            {   .header = " TTT " VERSION " ",  .width = -1,    .alignment = 'L'    },
            {   .header = " S ",        .width = 5,     .alignment = 'C'    },
            {   .header = " M ",        .width = 5,     .alignment = 'C'    },
            {   .header = " T ",        .width = 5,     .alignment = 'C'    },
            {   .header = " W ",        .width = 5,     .alignment = 'C'    },
            {   .header = " T ",        .width = 5,     .alignment = 'C'    },
            {   .header = " F ",        .width = 5,     .alignment = 'C'    },
            {   .header = " S ",        .width = 5,     .alignment = 'C'    },
            {   .header = " # ",        .width = 5,     .alignment = 'C'    },
        }
    };
    
    // Calculate alignment_offsets.
    for (layout_st *layout = layouts; layout < layouts + NUM_LAYOUTS; layout++) {
        for (column_st *col = layout->columns; col < layout->columns + NUM_COLUMNS; col++) {
            int offset;
            switch(col->alignment) {
                default:
                case 'L':
                    offset = 0;
                    break;
                    
                case 'C':
                    offset = ((col->width - strlen(col->header)) / 2);
                    break;
                    
                case 'R':
                    offset = (col->width - strlen(col->header));
                    break;
            }
            col->alignment_offset = offset;
        }
    }
    
    setlocale(LC_ALL, "C.UTF-8");   // Sets locale for C library functions; Allows usage of UTF-8.
    initscr();                      // Start curses mode.
    cbreak();                       // Line buffering disabled; pass on everty thing to me.
    keypad(stdscr, TRUE);           // I need that nifty F1.
    curs_set(0);                    // Set cursor invisible.
    noecho();                       // Disable echoing input characters.
    
    // Initialize pairs of colors.
    start_color();
    use_default_colors(); // Using default (-1) instead of COLOR_BLACK.
    init_pair(STYLE_SELECTED, COLOR_BLACK, COLOR_CYAN);
    init_pair(STYLE_SELECTED_INVERTED, COLOR_CYAN, -1);
    init_pair(STYLE_ACTIVE, COLOR_BLUE, -1);
    init_pair(STYLE_ACTIVE_SELECTED, COLOR_WHITE, COLOR_BLUE);
    init_pair(STYLE_ERROR, COLOR_RED, -1);
}

void update_layout() {
    // Calculate number of available rows to display tasks.
    layout_tasks_rows = (size_y - NUM_HEADER_ROWS - NUM_FOOTER_ROWS);
    
    // Calculate first column width: expands to fill the remaining space dynamically.
    for (layout_st *layout = layouts; layout <= &layouts[NUM_LAYOUTS - 1]; layout++) {
        layout->columns[0].width = size_x - (NUM_COLUMNS - 1) - 2;
        for (int idx = 1; idx < NUM_COLUMNS; idx++) {
            layout->columns[0].width -= layout->columns[idx].width;
        }
    }
}

void draw_tui(database_st *db, layout_st *layout) {
    
    const static int adjust_first_day_of_week[] = {
        (0 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
        (1 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
        (2 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
        (3 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
        (4 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
        (5 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
        (6 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
    };
    
    int x, y;
    column_st *col;
    
    // Get context information.
    task_st *active_task = get_active_task(db);
    task_st *selected_task = get_selected_task(db);
    time_t now_utc = time(NULL);
    int now_week_day = localtime(&now_utc)->tm_wday;

    // Reset theme and clear screen.
    attrset(A_NORMAL);
    erase();
    
    // Draw outer border.
    box(stdscr, 0, 0);
    
    // Draw table grids.
    y = 0;
    x = 0;
    for (int idx = 0; idx < NUM_COLUMNS - 1; idx++) {
        x += 1 + layout->columns[idx].width;
        mvaddch(y, x, ACS_TTEE);
        for (y = 1; y < size_y - 1; y++) {
            mvaddch(y, x, ACS_VLINE);
        }
        mvaddch(size_y - 1, x, ACS_BTEE);
    }
    
    
    ///////////////////////////////////////////////////////////////////////////
    // Draw headers.
    y = 0;
    x = 0;
    
    // Headers : title
    x++;
    col = &layout->columns[L_TITLE_IDX];
    mvaddstr(y, x + col->alignment_offset, (db == &archive ? layout->archive_title : col->header));
    x += col->width;
    
    // Headers : days
    for (int raw_idx = 0; raw_idx < NUM_WEEK_DAYS; raw_idx++) {
        int idx = adjust_first_day_of_week[raw_idx];
        x++;
        
        // Apply theme.
        if (idx == now_week_day && active_task != NULL) {
            attron(COLOR_PAIR(STYLE_ACTIVE) | A_BOLD);
        }
        else if (idx == now_week_day) {
            attron(COLOR_PAIR(STYLE_SELECTED_INVERTED) | A_BOLD);
        }
        
        col = &layout->columns[L_DAYS_IDX + idx];
        mvaddstr(y, x + col->alignment_offset, col->header);
        x += col->width;
        
        // Reset theme.
        attrset(A_NORMAL);
    }
    
    // Headers : total
    x++;
    col = &layout->columns[L_TOTAL_IDX];
    mvaddstr(y, x + col->alignment_offset, col->header);
    
    
    ///////////////////////////////////////////////////////////////////////////
    // Draw tasks.

    uint64_t total_time = 0;
    int column_width;
    
    y = 0;
    // Pagination based on currently selected task (show page where selected task is).
    size_t idx_start = (db->selected_task / layout_tasks_rows) * layout_tasks_rows;
    // Display up to rows allowed by the layout, or less if reached end of database.
    size_t idx_stop = idx_start + (layout_tasks_rows > db->count - idx_start ? db->count - idx_start : layout_tasks_rows);
    for (size_t idx = idx_start; idx < idx_stop; idx++) {
        task_st *task = &db->tasks[idx];
        y++;
        x = 0;
        
        // Apply theme.
        if (task == active_task && task == selected_task) {
            attron(COLOR_PAIR(STYLE_ACTIVE_SELECTED) | A_BOLD);
        }
        else if (task == selected_task) {
            attron(COLOR_PAIR(STYLE_SELECTED));
        }
        else if (task == active_task) {
            attron(COLOR_PAIR(STYLE_ACTIVE) | A_BOLD);
        }
        
        // Task title.
        x++;
        column_width = layout->columns[L_TITLE_IDX].width;
        mvprintw(y, x, "%-*.*s", column_width, column_width, task->name);
        x += column_width;
        
        // Task times.
        total_time = 0;
        for (int idx = 0; idx < NUM_WEEK_DAYS; idx++) {
            x++;
            
            int day_idx = (idx + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS;
            
            column_width = layout->columns[L_DAYS_IDX + day_idx].width;
            int64_t task_stime = task->times[day_idx];
            total_time = add_int64(total_time, task_stime);
            mvprintw_time(y, x, task_stime, column_width);
            x += column_width;
        }
        
        // Task total.
        x++;
        mvprintw_time(y, x, total_time, layout->columns[L_TOTAL_IDX].width);
        
        // Reset theme.
        attrset(A_NORMAL);
    }
    
    
    ///////////////////////////////////////////////////////////////////////////
    // Draw selected/total tasks.
    int size = snprintf(NULL, 0, " %td/%zd ", db->selected_task + 1, db->count);
    if (size <= layout->columns[L_TITLE_IDX].width) {
        mvprintw(size_y - 1, 1, " %td/%zd ", db->selected_task + 1, db->count);
    }
    else {
        mvprintw(size_y - 1, 1, "%td", db->selected_task + 1);
    }
    
    ///////////////////////////////////////////////////////////////////////////
    // Draw daily totals.
    y = size_y - 1;
    x = 0 + 1 + layout->columns[L_TITLE_IDX].width;
    total_time = 0;
    for (int raw_idx = 0; raw_idx < NUM_WEEK_DAYS; raw_idx++) {
        int idx = adjust_first_day_of_week[raw_idx];
        int64_t daily_total = db->total_times[idx];
        x++;
        
        // Apply theme.
        if (idx == now_week_day && active_task != NULL) {
            attron(COLOR_PAIR(STYLE_ACTIVE) | A_BOLD);
        }
        else if (idx == now_week_day) {
            attron(COLOR_PAIR(STYLE_SELECTED_INVERTED) | A_BOLD);
        }
        
        column_width = layout->columns[L_DAYS_IDX + idx].width;
        total_time = add_int64(total_time, daily_total);
        mvprintw_time(y, x, daily_total, column_width);
        x += column_width;
        
        // Reset theme.
        attrset(A_NORMAL);
    }
    x++;
    mvprintw_time(y, x, total_time, layout->columns[L_TOTAL_IDX].width);
}

void *mem_alloc(size_t mem_size, const char *error_tag) {
    void *mem_pointer = malloc(mem_size);
    if (mem_pointer == NULL && mem_size > 0) {
        print_error("Failed to allocate memory (%s): %s.", (error_tag == NULL ? "undefined" : error_tag), strerror(errno));
        exit(EXIT_FAILURE);
    }
    return mem_pointer;
}

*/
free_memory :: () {
    print(">> FREE <<\n");
    /* TODO
    reset_database(&database);
    reset_database(&archive);
    
    free(string_buffer);    string_buffer = NULL;
    free(app_directory);       app_directory = NULL;
    free(db_file_path);     db_file_path = NULL;
    free(ar_file_path);     ar_file_path = NULL;
    */
}

/*
void exit_gracefully(int signal) {
    flushinp();
    ungetch('q');
}

void read_input_to_string_buffer_with_space(int row, int column, int style, int length, int space) {
    assert(length < string_buffer_size);
    assert(space < string_buffer_size);
    
    attron(style | A_UNDERLINE);
    mvprintw(row, column, "%*s", space, "");
    echo();
    curs_set(1);
    memset(string_buffer, 0, string_buffer_size);
    mvgetnstr(row, column, string_buffer, length);
    truncate_string_utf8(string_buffer, length);
    noecho();
    curs_set(0);
    attrset(A_NORMAL);
}

void read_input_to_string_buffer(int row, int column, int style, int length) {
    read_input_to_string_buffer_with_space(row, column, style, length, length);
}

// Returns success.
bool read_input_to_int(int row, int style, const char *message, intmax_t *result) {
    assert(message != NULL);
    assert(result != NULL);
    
    attron(style);
    move(row, 1);
    addch(ACS_CKBOARD);
    addstr(message);
    attrset(A_NORMAL);
    
    // Get line number.
    int input_pos_x = getcurx(stdscr);
    int input_width = size_x - input_pos_x - 1;
    read_input_to_string_buffer(row, input_pos_x, style, input_width);
    
    char *parser;
    errno = 0;
    *result = strtoimax(string_buffer, &parser, 10);
    
    bool success = (errno == 0 || errno == ERANGE)  // No error OR value was clamped to limits (acceptable).
        && parser != string_buffer; // If no digits are found, parser will return the address of the input string.
    
    return success;
}

// Retuns true if user presses enter, false otherwise.
bool read_enter_confirmation(int row, int style, const char *message) {
    assert(message != NULL);
    
    attron(style);
    move(row, 1);
    for (int idx = 0; idx < size_x - 2; idx++) {
        addch(ACS_CKBOARD);
    }
    mvaddstr(row, 2, message);
    attrset(A_NORMAL);
    
    return getch() == '\n';
}
*/

main :: () {

    print("---\n");

    format :: (value: string) {
        print("value is '%'\n", value);
    }

    format("direct");
    va := "var A";
    format(va);

    sb := "var B";
    vb: [2048] u8;
    memcpy(vb.data, sb.data, sb.count);
    xb: string = xx sb;
    print("> xb.count = %\n> xb.data = %\n", xb.count, xb.data);
    format(xx vb);

    print("--- --- ---\n");
    xpto: string = "ç€dam";
    truncate_string_utf8(xpto, 3);
    print(">'%'\n", xpto);

    return;

    
    defer free_memory();
    
    {   // Initialize app directory.
        home_dir, success_dir := get_home_directory(); // Returns system owned memory.
        if success_dir == false {
            home_dir = ".";
        }
        
        home_path, success_path := get_absolute_path(home_dir); // Returns temporary memory.
        if success_path == false {
            print_error("Failed to find home directory '%'.", home_dir);
            return;
        }
        
        app_directory = join(home_path, "/", APP_FOLDER_NAME);
        db_file_path = join(app_directory, "/", DB_FILE_NAME);
        ar_file_path = join(app_directory, "/", AR_FILE_NAME);
    }

    
    db      : Database;
    {
        import_from_csv(*db, ar_file_path);
        
//         for db.tasks print_task(it);
        
        print_task :: (task: Task) {
            for task.times print("% |", it);
            print(" %\n", cast(string)task.name);
        }
        return;
        
        
        // Stores data from database into binary file.
        // Returns success.
        store_database :: (db: Database, path: string) -> success: bool {
            //assert(db != null, "Parameter 'db' is null.");
            assert(xx path, "Parameter 'path' is empty.");
            
            // Open file.
            file, open_success := file_open(path, for_writing = true); // log_errors: bool = true
            if open_success == false {
                print_error("Failed to open file '%' while storing database: ERROR_FROM_LOG", path); // TODO Get error from logger ?!
                return false;
            }
            defer file_close(*file);
            
            file_write(*file, DB_FILE_SIGN_STR);
            file_write(*file, *db, size_of(Database));
            //fwrite(DB_FILE_SIGN, SIZEOF_CHAR, DB_FILE_SIGN_LENGTH, file);
            //fwrite(db, SIZEOF_DATABASE_ST, 1, file);
            //fwrite(db->tasks, SIZEOF_TASK_ST, db->count, file);

            return true;
        }
       
        // Loads data from binary file into database.
        // Returns success.
        load_database :: (db: *Database, path: string) -> success: bool {
            assert(db != null, "Parameter 'db' is null.");
            assert(xx path, "Parameter 'path' is empty.");
            
            // Open file.
            file, open_success := file_open(path); // log_errors: bool = true
            if open_success == false {
                print_error("Failed to open file '%' while loading database: ERROR_FROM_LOG", path); // TODO Get error from logger ?!
                return false;
            }
            defer file_close(*file);
            
            // Validate file signature.
            file_signature: [DB_FILE_SIGN_STR.count] u8;
            read_success := file_read(file, *file_signature, DB_FILE_SIGN_STR.count);
            if read_success == false print_error("Failed to read file signature from '%'.", path);
            if cast(string)file_signature != DB_FILE_SIGN_STR {
                print_error("Invalid file signature.");
                file_close(*file);
                return false;
            }
            
            // Read database structure.
            
            read_success = file_read(file, db, size_of(Database));
            //if read_success == false print_error("Failed to read database info from '%'.", path);  
            
            
            //file_open :: (name: string, for_writing := false, keep_existing_content := false, log_errors := true) -> File, bool 
            //file_read :: (f: File, vdata: *void, bytes_to_read: s64) -> (success: bool, total_read: s64) 
            
            return true;
        }
        
        
        // Loads data from binary file into database.
        // Returns success.
        /*
        load_database :: (
        
        
        bool load_database(database_st *db, const char *path) {
            assert(db != NULL);
            assert(path != NULL);
            
            // Open file.
            FILE *file = fopen(path, "rb");
            if (file == NULL) {
                print_error("Failed to open file '%s' while loading database: %s.", path, strerror(errno));
                return false;
            }
            
            // Validate file signature.
            char file_signature[DB_FILE_SIGN_LENGTH];
            fread(&file_signature, SIZEOF_CHAR, DB_FILE_SIGN_LENGTH, file);
            if (strncmp(file_signature, DB_FILE_SIGN, DB_FILE_SIGN_LENGTH) != 0) {
                print_error("Invalid file signature.");
                fclose(file);
                return false;
            }
            
            // Read database structure.
            fread(db, SIZEOF_DATABASE_ST, 1, file);
            
            // Reserve database capacity for tasks.
            size_t capacity_bytes = db->capacity * SIZEOF_TASK_ST;
            db->tasks = malloc(capacity_bytes);
            if (db->tasks == NULL && capacity_bytes > 0) {
                print_error("Failed to allocate memory while loading database: %s.", strerror(errno));
                return false;
            }
            
            // Read database tasks.
            fread(db->tasks, SIZEOF_TASK_ST, db->count, file);
            
            // Make sure we are reading all the file.
            assert(fgetc(file) == EOF);
            
            fclose(file);
            return true;
        }
    */
    }
    
    return; // TODO DEBUG
    
    /*
    db = &database;
    reset_database(&database);
    reset_database(&archive);
    
    if (is_file_accessible(db_file_path) == false) {
        if (store_database(&database, db_file_path) == false) {
            print_error("Failed to initialize database.");
            return;
        }
    }
    
    if (is_file_accessible(ar_file_path) == false) {
        if (export_to_csv(&archive, ar_file_path) == false) {
            print_error("Failed to initialize archive.");
            return;
        }
    }
    */
    
    args :=  get_command_line_arguments();
    defer  array_reset(*args);
    
    if args.count > 1 {
        
        is_exit_requested := false;
        for 1..args.count-1 {
            if is_equal_to_any(args[it], "--help", "-h") {
                write_strings(
                    "Usage: ttt [OPTION]... [FILE]...\n",
                    "  -i, --import-csv [FILE]       Import CSV file to database (discard first row).\n",
                    "  -e, --export-csv [FILE]       Export database to CSV file.\n",
                    "  -n, --no-autosave             Disable autosave feature (only save on exit).\n",
                    "  -h, --help                    Display this help and exit.\n",
                    "  -v, --version                 Output version information and exit.\n",
                    "\n",
                    "In app commands\n",
                    "  a, A                          Archive selected task (except if active).\n",
                    "  r, R                          Restore selected task from archive.\n",
                    "  t, T                          Select currently active task (if any).\n",
                    "  d, D                          Duplicate selected task.\n",
                    "  n, N                          Create new task.\n",
                    "  m, M                          Move selected task to position.\n",
                    "  g, G                          Select task by position.\n",
                    "  q, Q                          Save changes and exit.\n",
                    "  F2                            Rename selected task.\n",
                    "  F5                            Recalculate total times.\n",
                    "  TAB                           Toggle archive view.\n",
                    "  BACKSPACE                     Reset times for selected task.\n",
                    "  DELETE                        Delete selected task (except if active).\n",
                    "  SPACE, ENTER                  Toggle selected task as active/inactive.\n",
                    "  1, 2, 3, 4, 5, 6, 7           Edit selected task time for the Nth day of week:\n",
                    "                                  =#    sets # seconds;\n",
                    "                                  -#    subtracts # seconds;\n",
                    "                                  #     adds # seconds;\n",
                    "                                  #m    specifies # as minutes;\n",
                    "                                  #h    specifies # as hours;\n",
                    "                                  #d    specifies # as days;\n",
                    "                                  #y    specifies # as years.\n",
                    "  UP                            Select task above.\n",
                    "  DOWN                          Select task below.\n",
                    "  PAGE-UP                       Select task 1 page above.\n",
                    "  PAGE-DOWN                     Select task 1 page below.\n",
                    "  HOME                          Select first/top task.\n",
                    "  END                           Select last/bottom task.\n",
                    "\n",
                    "Notes\n");
                print("- All data files are stored in '%'.\n", app_directory);
                print("  If the home directory is undefined, './%' will be used.\n", APP_FOLDER_NAME);
                write_strings(
                    "  The database entries are stored in binary format on the 'database.bin' file.\n",
                    "  The archived entries are stored in CSV format on the 'archive.csv' file.\n",
                    "- During intensive tasks such as saving to file or recalculating totals times,\n",
                    "  a diamond symbol is shown on the top left corner.\n"
                );
                return;
            }
            
            if is_equal_to_any(args[it], "--version", "-v") {
                print("Task Time Tracker version % \nCopyright % Daniel Martins\nLicense GPL-3.0-or-later\n", VERSION, YEAR);
                return;
            }
            
            if is_equal_to_any(args[it], "--import-csv", "-i") {
                it += 1;
                if it >= args.count {
                    print_error("Missing CSV file path to import.");
                    return;
                }
                // TODO Implement
//                 if (load_database(&database, db_file_path) == false) {
//                     print_error("Failed to load database.");
//                     return;
//                 }
//                 if (import_from_csv(&database, args[it]) == false) {
//                     print_error("Failed to import CSV file.");
//                     return;
//                 }
//                 if (store_database(&database, db_file_path) == false) {
//                     print_error("Failed to store database.");
//                     return;
//                 }
//                 reset_database(&database);
                is_exit_requested = true;
                continue;
            }
            
            if is_equal_to_any(args[it], "--export-csv", "-e") {
                it += 1;
                if it >= args.count {
                    print_error("Missing CSV file path to export.");
                    return;
                }
                // TODO Implement
//                 if (load_database(&database, db_file_path) == false) {
//                     print_error("Failed to load database.");
//                     return;
//                 }
//                 if (export_to_csv(&database, args[it]) == false) {
//                     print_error("Failed to export CSV file.");
//                     return;
//                 }
//                 reset_database(&database);
                is_exit_requested = true;
                continue;
            }
            
            if is_equal_to_any(args[it], "--no-autosave", "-n") {
                is_autosave_enabled = false;
                continue;
            }
            
            print_error("%: invalid option '%'.\nTry '% --help' for more information.", args[0], args[it], args[0]);
            return;
        }
        
        if is_exit_requested {
            return;
        }
    }
    
    /*
    if (load_database(&database, db_file_path) == false) {
        print_error("Failed to load database.");
        return;
    }
    
    initialize_tui();
    
    signal(SIGTERM, exit_gracefully);
    signal(SIGINT, exit_gracefully);
    signal(SIGQUIT, exit_gracefully);
    signal(SIGHUP, exit_gracefully);
    
    flushinp();
    ungetch(KEY_RESIZE);
    for (int key; ((key = getch()) != 'q') && (key != 'Q'); ) {
        
        static layout_st *layout = &layouts[L_COMPACT];
        task_st *active_task = get_active_task(db);
        task_st *selected_task = get_selected_task(db);
        int action_style = A_BOLD | COLOR_PAIR(selected_task == active_task && selected_task != NULL ? STYLE_ACTIVE : STYLE_SELECTED_INVERTED);
        int error_style =  A_BOLD | COLOR_PAIR(STYLE_ERROR);
        int selected_task_row = is_terminal_too_small ? 0
            : (db->selected_task < 0) ? 1
            : (db->selected_task % layout_tasks_rows) + NUM_HEADER_ROWS;
        
        timeout(INPUT_AWAIT_INF);
        update_times(&database);
        
        switch(key) {
            
            // When getch() times out.
            case ERR: {
                if (is_autosave_enabled && countdown_to_autosave > 0) {
                    countdown_to_autosave -= INPUT_TIMEOUT_MS;
                    if (countdown_to_autosave <= 0) {
                        show_processing();
                        if (db == &archive) {
                            export_to_csv(&archive, ar_file_path);
                        }
                        store_database(&database, db_file_path);
                    }
                }
                break;
            }
            
            // When terminal is resized.
            case KEY_RESIZE: {
                clear();
                getmaxyx(stdscr, size_y, size_x);
                is_terminal_too_small = size_x < 60 || size_y < 3;
                size_t new_size = 2047 | TASK_NAME_BYTES | (size_x + 1);
                if (string_buffer_size < new_size) {
                    string_buffer_size = new_size;
                    string_buffer = realloc(string_buffer, string_buffer_size);
                    if (string_buffer == NULL && string_buffer_size > 0) {
                        print_error("Failed to allocate memory for string buffer: %s.", strerror(errno));
                        flushinp();
                        ungetch('q');
                        break;
                    }
                }
                update_layout();
                layout = &layouts[size_x > 100 ? L_NORMAL : L_COMPACT];
                break;
            }
            
            case 'n':
            case 'N':{
                if (is_database_full(db)) {
                    read_enter_confirmation(selected_task_row, error_style, " Unable to create entry: database is full. ");
                    break;
                }
                
                // Create new task.
                task_st *new_task;
                if (create_task(db, &new_task) == false) {
                    break;
                }
                
                // Set new task name.
                time_t now_utc = time(NULL);
                struct tm *now_local = localtime(&now_utc);
                strftime(new_task->name, TASK_NAME_BYTES, "%Y-%m-%d %H:%M:%S", now_local);
                
                // Select new task.
                select_task(db, new_task);
                selected_task = get_selected_task(db);
                trigger_autosave();
                
                // Force rename action.
                flushinp();
                ungetch(KEY_F(2));
                break;
            }
            
            case KEY_F(2): {
                if (selected_task == NULL) {
                    break;
                }
                
                read_input_to_string_buffer_with_space(selected_task_row, 1, action_style, TASK_NAME_LENGTH, size_x - 2);
                if (is_empty_string(string_buffer) == false) {
                    replace_char(string_buffer, '\t', ' ');
                    replace_char(string_buffer, '\v', ' ');
                    replace_char(string_buffer, '\f', ' ');
                    replace_char(string_buffer, '\r', ' ');
                    memcpy(selected_task->name, string_buffer, TASK_NAME_BYTES);
                    trigger_autosave();
                }
                break;
            }
            
            case KEY_BACKSPACE: {
                if (selected_task == NULL) {
                    break;
                }
                
                if (read_enter_confirmation(selected_task_row, action_style, " Press enter to reset task. ") == true) {
                    reset_task_times(db, selected_task);
                    trigger_autosave();
                }
                break;
            }
            
            case KEY_DC: { // Delete
                if (selected_task == NULL || selected_task == active_task) {
                    break;
                }
                
                if (read_enter_confirmation(selected_task_row, action_style, " Press enter to delete task. ") == true) {
                    delete_task(db, selected_task);
                    trigger_autosave();
                }
                break;
            }
            
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7': {
                if (selected_task == NULL) {
                    break;
                }
                
                // Prepare position to input time operation.
                int selected_day = key - '1';
                int input_width = layout->columns[L_DAYS_IDX + selected_day].width;
                int input_pos_x = 1 + layout->columns[L_TITLE_IDX].width;
                for (int col = 0; col < selected_day; col++) {
                    input_pos_x += 1 + layout->columns[L_DAYS_IDX + col].width;
                }
                input_pos_x++;
                
                // Get input string.
                read_input_to_string_buffer(selected_task_row, input_pos_x, action_style, input_width);
                char *input = string_buffer;
                
                // Abort if input if empty.
                if (is_empty_string(input) == true) {
                    break;
                }
                
                // Search for assign '=' operator and discard everything before (if found).
                char *assign_str = strchr(input, '=');
                bool is_assign = assign_str != NULL;
                if (is_assign == true) {
                    input = assign_str + 1;
                }
                
                // Try to parse a number and abort if it fails.
                char *parser;
                long double input_float = strtold(input, &parser);
                if (parser == input) {
                    break;
                }
                input = parser;
                
                // Try to parse a character representing the time multiplier.
                long double multiplier = 1.0;
                for (int i=0; i < strlen(input); i++) {
                    char ch = input[i];
                    if (ch == 'm' || ch == 'M') {
                        multiplier = SECONDS_IN_MINUTE;
                        break;
                    }
                    else if (ch == 'h' || ch == 'H') {
                        multiplier = SECONDS_IN_HOUR;
                        break;
                    }
                    else if (ch == 'd' || ch == 'D') {
                        multiplier = SECONDS_IN_DAY;
                        break;
                    }
                    else if (ch == 'y' || ch == 'Y') {
                        multiplier = SECONDS_IN_YEAR;
                        break;
                    }
                }
                
                // Process input and check if it's valid.
                long double input_time = input_float * multiplier;
                bool is_result_valid = (input_time >= (long double)INT64_MIN && input_time <= (long double)INT64_MAX);
                if (is_result_valid == false) {
                    break;
                }
                
                // Apply changes.
                int64_t time = input_time;
                int day = (selected_day + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS;
                if (is_assign == true) {
                    set_task_time(db, selected_task, day, time);
                }
                else {
                    add_task_time(db, selected_task, day, time);
                }
                trigger_autosave();
                break;
            }
            
            case 'm':
            case 'M': {
                if (selected_task == NULL) {
                    break;
                }
                
                intmax_t value;
                if (read_input_to_int(selected_task_row, action_style, " Move to: ", &value) == false) {
                    break;
                }
                
                ptrdiff_t target_index = (value < 1 ? 1 : value > MAX_DATABASE_TASKS ? MAX_DATABASE_TASKS : value) - 1;
                move_task_to_index(db, selected_task, target_index);
                trigger_autosave();
                break;
            }
            
            case 'g':
            case 'G': {
                if (selected_task == NULL) {
                    break;
                }
                
                intmax_t value;
                if (read_input_to_int(selected_task_row, action_style, " Go to: ", &value) == false) {
                    break;
                }
                
                ptrdiff_t target_index = (value < 1 ? 1 : value > MAX_DATABASE_TASKS ? MAX_DATABASE_TASKS : value) - 1;
                select_task_by_index(db, target_index);
                break;
            }
            
            case 'd':
            case 'D':{
                if (selected_task == NULL) {
                    break;
                }
                
                if (is_database_full(db)) {
                    read_enter_confirmation(selected_task_row, error_style, " Unable to duplicate entry: database is full. ");
                    break;
                }
                
                if (duplicate_task(db, selected_task) == false) {
                    break;
                }
                trigger_autosave();
                break;
            }
            
            case KEY_F(5): {
                update_total_times(db);
                trigger_autosave();
                break;
            }
            
            case 't':
            case 'T': {
                if (active_task == NULL) {
                    break;
                }
                select_task(db, active_task);
                break;
            }
            
            case '\n':
            case ' ': {
                if (db != &database || selected_task == NULL) {
                    break;
                }
                set_active_task(db, (active_task == selected_task) ? NULL : selected_task);
                active_task = get_active_task(db);
                trigger_autosave();
                break;
            }
            
            case '\t': {
                if (db == &database) {
                    if (import_from_csv(&archive, ar_file_path) == false) {
                        reset_database(&archive);
                        print_error("Failed to load archive.");
                        break;
                    }
                    db = &archive;
                }
                else {
                    if (export_to_csv(&archive, ar_file_path) == false) {
                        print_error("Failed to store archive.");
                        break;
                    }
                    reset_database(&archive);
                    db = &database;
                }
                break;
            }
            
            case 'a':
            case 'A': {
                if (db != &database || selected_task == NULL || selected_task == active_task) {
                    break;
                }
                if (append_to_csv(selected_task, ar_file_path) == false) {
                    print_error("Failed to archive entry.");
                    break;
                }
                delete_task(&database, selected_task);
                trigger_autosave();
                break;
            }
            
            case 'r':
            case 'R': {
                if (db != &archive || selected_task == NULL) {
                    break;
                }
                if (is_database_full(&database)) {
                    read_enter_confirmation(selected_task_row, error_style, " Unable to restore entry: database is full. ");
                    break;
                }
                if (duplicate_task(&database, selected_task) == false) {
                    print_error("Failed to restore entry.");
                    break;
                }
                delete_task(&archive, selected_task);
                trigger_autosave();
                break;
            }
            
            case KEY_HOME: {
                select_task_by_index(db, 0);
                break;
            }
            
            case KEY_UP: {
                select_task_by_delta(db, -1);
                break;
            }
            
            case KEY_PPAGE: {
                select_task_by_delta(db, -layout_tasks_rows);
                break;
            }
            
            case KEY_END: {
                select_task_by_index(db, db->count-1);
                break;
            }
            
            case KEY_DOWN: {
                select_task_by_delta(db, 1);
                break;
            }
            
            case KEY_NPAGE: {
                select_task_by_delta(db, layout_tasks_rows);
                break;
            }
        }
        
        if (is_terminal_too_small) {
            const char *INVALID_WINDOW_MESSAGE = "Terminal is too small: minimum 60x3.";
            const int INVALID_WINDOW_MESSAGE_LENGTH = strlen(INVALID_WINDOW_MESSAGE);
            mvaddstr(size_y / 2, (size_x - INVALID_WINDOW_MESSAGE_LENGTH) / 2, INVALID_WINDOW_MESSAGE);
        }
        else {
            draw_tui(db, layout);
            draw_error_window();
        }
        
        timeout(INPUT_TIMEOUT_MS);
    }
    
    // Save any unsaved changes.
    show_processing();
    bool error_saving = false;
    if (db == &archive) {
        if (export_to_csv(&archive, ar_file_path) == false) {
            print_error("Failed to save archive.");
            error_saving |= true;
        }
    }
    if (countdown_to_autosave > 0 || is_autosave_enabled == false) {
        if (store_database(&database, db_file_path) == false) {
            print_error("Failed to save database.");
            error_saving |= true;
        }
    }
    if (error_saving) {
        print_error("Press any key to close.");
        draw_error_window();
        timeout(INPUT_AWAIT_INF);
        getch();
    }
    
    endwin();
    return error_saving ? EXIT_FAILURE : EXIT_SUCCESS;
    */
}


/*
main :: () {
    
    print("TNL %\n", TASK_NAME_LENGTH);
    print("TNB %\n", TASK_NAME_BYTES);
    
    home, success := get_home_directory();
    print("home '%' | success '%'\n", home, success);
    
    print("Task Time Tracker version %\n", VERSION);
    print("Copyright 2022 Daniel Martins\n");
    print("License GPL-3.0-or-later\n");
    
// TODO More binding examples here https://github.com/vrcamillo/jai-tracy
//     short   : s16
//     int     : s32
//     long    : s64 (int)
//     single  : float32 (float)
//     double  : float64

    stdscr := initscr();
    curs_set(0);
    noecho();
    box(stdscr, 0, 0);
    while true {
        key := getch();
        if key == #char "q" break;
        mvaddstr(1, 1, "> wow alçapão <");
    }
    endwin();
        
}
*/


print_owner_allocator :: (tag: string, memory: *void) {
    owner := "unkown";
    
    if true == xx context.allocator.proc(.IS_THIS_YOURS, 0, 0, memory, null) then owner = "default";
    else if true == xx temp.proc(.IS_THIS_YOURS, 0, 0, memory, null) then owner = "temp";

    print("'%' belongs to '%'\n", tag, owner);
}