File: sys_display.c

package info (click to toggle)
iverilog 0.9.5-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 6,732 kB
  • sloc: cpp: 69,595; ansic: 39,290; yacc: 5,343; sh: 3,231; makefile: 1,174
file content (2221 lines) | stat: -rw-r--r-- 73,252 bytes parent folder | download
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
/*
 * Copyright (c) 1999-2011 Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form under the terms of the GNU
 *    General Public License as published by the Free Software
 *    Foundation; either version 2 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, write to the Free Software
 *    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

# include  "sys_priv.h"
# include  <assert.h>
# include  <string.h>
# include  <errno.h>
# include  <ctype.h>
# include  <stdio.h>
# include  <stdlib.h>
# include  <math.h>

#define IS_MCD(mcd)     !((mcd)>>31&1)

/* Printf wrapper to handle both MCD/FD */
static PLI_INT32 my_mcd_printf(PLI_UINT32 mcd, const char *fmt, ...)
{
      int r = 0;

      va_list ap;
      va_start(ap, fmt);

      if (IS_MCD(mcd)) {
	    r = vpi_mcd_vprintf(mcd, fmt, ap);
      } else {
	    FILE *fp = vpi_get_file(mcd);
	    if (fp) r = vfprintf(fp, fmt, ap);
      }

      va_end(ap);
      return r;
}

struct timeformat_info_s timeformat_info = { 0, 0, 0, 20 };

struct strobe_cb_info {
      const char*name;
      char*filename;
      int lineno;
      int default_format;
      vpiHandle scope;
      vpiHandle*items;
      unsigned nitems;
      unsigned fd_mcd;
};

/*
 * The number of decimal digits needed to represent a
 * nr_bits binary number is floor(nr_bits*log_10(2))+1,
 * where log_10(2) = 0.30102999566398....  and I approximate
 * this transcendental number as 146/485, to avoid the vagaries
 * of floating-point.  The smallest nr_bits for which this
 * approximation fails is 2621,
 * 2621*log_10(2)=789.9996, but (2621*146+484)/485=790 (exactly).
 * In cases like this, all that happens is we allocate one
 * unneeded char for the output.  I add a "L" suffix to 146
 * to make sure the computation is done as long ints, otherwise
 * on a 16-bit int machine (allowed by ISO C) we would mangle
 * this computation for bit-length of 224.  I'd like to put
 * in a test for nr_bits < LONG_MAX/146, but don't know how
 * to fail, other than crashing.
 *
 * In an April 2000 thread in comp.unix.programmer, with subject
 * "integer -> string", I <LRDoolittle@lbl.gov> give the 28/93
 * approximation, but overstate its accuracy: that version first
 * fails when the number of bits is 289, not 671.
 *
 * This result does not include space for a trailing '\0', if any.
*/
__inline__ static int calc_dec_size(int nr_bits, int is_signed)
{
	int r;
	if (is_signed) --nr_bits;
	r = (nr_bits * 146L + 484) / 485;
	if (is_signed) ++r;
	return r;
}

static int vpi_get_dec_size(vpiHandle item)
{
	return calc_dec_size(
		vpi_get(vpiSize, item),
		vpi_get(vpiSigned, item)==1
	);
}

static void array_from_iterator(struct strobe_cb_info*info, vpiHandle argv)
{
      if (argv) {
	    vpiHandle item;
	    unsigned nitems = 1;
	    vpiHandle*items = malloc(sizeof(vpiHandle));
	    items[0] = vpi_scan(argv);
	    if (items[0] == 0) {
		  free(items);
		  info->nitems = 0;
		  info->items  = 0;
		  return;
	    }

	    for (item = vpi_scan(argv) ;  item ;  item = vpi_scan(argv)) {
		  items = realloc(items, (nitems+1)*sizeof(vpiHandle));
		  items[nitems] = item;
		  nitems += 1;
	    }

	    info->nitems = nitems;
	    info->items = items;

      } else {
	    info->nitems = 0;
	    info->items = 0;
      }
}

static int get_default_format(const char *name)
{
    int default_format;

    switch(name[ strlen(name)-1 ]){
	/*  writE/strobE or monitoR or displaY/fdisplaY or sformaT */
    case 'e':
    case 'r':
    case 't':
    case 'y': default_format = vpiDecStrVal; break;
    case 'h': default_format = vpiHexStrVal; break;
    case 'o': default_format = vpiOctStrVal; break;
    case 'b': default_format = vpiBinStrVal; break;
    default:
	default_format = -1;
	assert(0);
    }

    return default_format;
}

/* Build the format using the variables that control how the item will
 * be printed. This is used in error messages and directly by the e/f/g
 * format codes (minus the enclosing <>). The user needs to free the
 * returned string. */
static char * format_as_string(int ljust, int plus, int ld_zero, int width,
                               int prec, char fmt)
{
  char buf[256];
  unsigned int size = 0;

  /* Do not remove/change the "<" without also changing the e/f/g format
   * code below! */
  buf[size++] = '<';
  buf[size++] = '%';
  if (ljust == 1) buf[size++] = '-';
  if (plus == 1) buf[size++] = '+';
  if (ld_zero == 1) buf[size++] = '0';
  if (width != -1)
    size += sprintf(&buf[size], "%d", width);
  if (prec != -1)
    size += sprintf(&buf[size], ".%d", prec);
  if (fmt) buf[size++] = fmt;
  /* The same goes here ">"! */
  buf[size++] = '>';
  buf[size] = '\0';
  return strdup(buf);
}

static void get_time(char *rtn, const char *value, int prec,
                     PLI_INT32 time_units)
{
  int head, tail;
  int shift = time_units - timeformat_info.units;

  /* Strip any leading zeros, but leave a single zero. */
  while (value[0] == '0' && value[1] != '\0') value += 1;
  /* We need to scale the number up. */
  if (shift >= 0) {
    strcpy(rtn, value);
    /* Shift only non-zero values. */
    while (shift > 0 && value[0] != '0') {
      strcat(rtn, "0");
      shift -= 1;
    }
    if (prec > 0) strcat(rtn, ".");
    while(prec > 0) {
      strcat(rtn, "0");
      prec -= 1;
    }

  /* We need to scale the number down. */
  } else {
    head = strlen(value) + shift;
    /* We have digits to the left of the decimal point. */
    if (head > 0) {
      strncpy(rtn, value, head);
      *(rtn+head) = '\0';
      if (prec > 0) {
        strcat(rtn, ".");
        strncat(rtn, &value[head], prec);
        tail = prec + shift;
        while (tail > 0) {
          strcat(rtn, "0");
          tail -= 1;
        }
      }
    /* All digits are to the right of the decimal point. */
    } else {
      strcpy(rtn, "0");
      if (prec > 0) strcat(rtn, ".");
      /* Add leading zeros as needed. */
      head = -shift - 1;
      if (head > prec) head = prec;
      while (head > 0) {
        strcat(rtn, "0");
        head -= 1;
      }
      /* Add digits from the value if they fit. */
      tail = prec + shift + 1;
      if (tail > 0) {
        strncat(rtn, value, tail);
        /* Add trailing zeros to fill out the precision. */
        tail = prec + shift + 1 - strlen(value);
        while (tail > 0) {
          strcat(rtn, "0");
          tail -= 1;
        }
      }
    }
  }

  strcat(rtn, timeformat_info.suff);
}

static void get_time_real(char *rtn, double value, int prec,
                          PLI_INT32 time_units)
{
  /* Scale the value from its time units to the format time units. */
  if (time_units >= timeformat_info.units) {
    value *= pow(10.0, time_units - timeformat_info.units);
  } else {
    value /= pow(10.0, timeformat_info.units - time_units);
  }
  sprintf(rtn, "%0.*f%s", prec, value, timeformat_info.suff);
}

static unsigned int get_format_char(char **rtn, int ljust, int plus,
                                    int ld_zero, int width, int prec,
                                    char fmt, const struct strobe_cb_info *info,
                                    unsigned int *idx)
{
  s_vpi_value value;
  char *result, *fmtb;
  unsigned int size;
  unsigned int ini_size = 512;  /* The initial size of the buffer. */

  /* Make sure the width fits in the initial buffer. */
  assert(width >= -1);
  if ((unsigned int)(width+1) > ini_size) ini_size = width + 1;

  /* The default return value is the full format. */
  result = malloc(ini_size*sizeof(char));
  fmtb = format_as_string(ljust, plus, ld_zero, width, prec, fmt);
  strcpy(result, fmtb);
  size = strlen(result) + 1; /* fallback value if errors */
  switch (fmt) {

    case '%':
    case '\0':
      if (ljust != 0  || plus != 0 || ld_zero != 0 || width != -1 ||
          prec != -1) {
        vpi_printf("WARNING: %s:%d: invalid format %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      }
      strcpy(result, "%");
      size = strlen(result) + 1;
      break;

    case 'b':
    case 'B':
    case 'o':
    case 'O':
    case 'h':
    case 'H':
    case 'x':
    case 'X':
      *idx += 1;
      if (plus != 0 || prec != -1) {
        vpi_printf("WARNING: %s:%d: invalid format %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      }
      if (*idx >= info->nitems) {
        vpi_printf("WARNING: %s:%d: missing argument for %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      } else {
        switch (fmt) {
          case 'b':
          case 'B':
            value.format = vpiBinStrVal;
            break;
          case 'o':
          case 'O':
            value.format = vpiOctStrVal;
            break;
          case 'h':
          case 'H':
          case 'x':
          case 'X':
            value.format = vpiHexStrVal;
            break;
        }
        vpi_get_value(info->items[*idx], &value);
        if (value.format == vpiSuppressVal) {
          vpi_printf("WARNING: %s:%d: incompatible value for %s%s.\n",
                     info->filename, info->lineno, info->name, fmtb);
        } else {
          unsigned swidth = strlen(value.value.str), free_flag = 0;;
          char *cp = value.value.str;

          if (ld_zero == 1) {
            /* Strip the leading zeros if a width is not given. */
            if (width == -1) while (*cp == '0' && *(cp+1) != '\0') cp++;
            /* Pad with leading zeros. */
            else if (ljust == 0 && (signed)swidth < width) {
              unsigned pad = (unsigned)width - swidth;
              cp = malloc((width+1)*sizeof(char));
              memset(cp, '0', pad);
              strcpy(cp+pad, value.value.str);
              free_flag = 1;
            /* For a left aligned value also strip the leading zeros. */
            } else if (ljust != 0) while (*cp == '0' && *(cp+1) != '\0') cp++;
          }

          /* If a width was not given, use a width of zero. */
          if (width == -1) width = 0;

          /* If the default buffer is too small, make it big enough. */
          size = strlen(cp) + 1;
          if ((signed)size < (width+1)) size = width+1;
          if (size > ini_size) result = realloc(result, size*sizeof(char));

          if (ljust == 0) sprintf(result, "%*s", width, cp);
          else sprintf(result, "%-*s", width, cp);
          if (free_flag) free(cp);
          size = strlen(result) + 1;
        }
      }
      break;

    case 'c':
    case 'C':
      *idx += 1;
      if (plus != 0 || prec != -1) {
        vpi_printf("WARNING: %s:%d: invalid format %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      }
      if (*idx >= info->nitems) {
        vpi_printf("WARNING: %s:%d: missing argument for %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      } else {
        value.format = vpiStringVal;
        vpi_get_value(info->items[*idx], &value);
        if (value.format == vpiSuppressVal) {
          vpi_printf("WARNING: %s:%d: incompatible value for %s%s.\n",
                     info->filename, info->lineno, info->name, fmtb);
        } else {
          char ch = value.value.str[strlen(value.value.str)-1];

          /* If the default buffer is too small, make it big enough. */
          size = width + 1;
          if (size > ini_size) result = realloc(result, size*sizeof(char));

          /* If the width is less than one then use a width of one. */
          if (width < 1) width = 1;
          if (ljust == 0) {
            if (width > 1) {
              char *cp = malloc((width+1)*sizeof(char));
              memset(cp, (ld_zero == 1 ? '0': ' '), width-1);
              cp[width-1] = ch;
              cp[width] = '\0';
              sprintf(result, "%*s", width, cp);
              free(cp);
            } else sprintf(result, "%c", ch);
          } else sprintf(result, "%-*c", width, ch);
          size = strlen(result) + 1;
        }
      }
      break;

    case 'd':
    case 'D':
      *idx += 1;
      if (prec != -1) {
        vpi_printf("WARNING: %s:%d: invalid format %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      }
      if (*idx >= info->nitems) {
        vpi_printf("WARNING: %s:%d: missing argument for %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      } else {
        value.format = vpiDecStrVal;
        vpi_get_value(info->items[*idx], &value);
        if (value.format == vpiSuppressVal) {
          vpi_printf("WARNING: %s:%d: incompatible value for %s%s.\n",
                     info->filename, info->lineno, info->name, fmtb);
        } else {
          unsigned pad = 0;
          unsigned swidth = strlen(value.value.str) +
                            (value.value.str[0] == '-' ? 0 : (unsigned)plus);
          char *tbuf, *cpb, *cp = value.value.str;

          /* Allocate storage and calculate the pad if needed. */
          if (ljust == 0 && ld_zero == 1 && (signed)swidth < width) {
            tbuf = malloc((width+1)*sizeof(char));
            pad = (unsigned)width - swidth;
          } else {
            tbuf = malloc((swidth+1)*sizeof(char));
          }
          cpb = tbuf;

          /* Insert the sign if needed. */
          if (plus == 1 && *cp != '-') {
            *cpb = '+';
            cpb += 1;
          } else if (*cp == '-') {
            *cpb = '-';
            cpb += 1;
            cp += 1;
          }

          /* Now add padding if it is needed and then add the value. */
          memset(cpb, '0', pad);
          strcpy(cpb+pad, cp);

          /* If a width was not given, use the default, unless we have a
           * leading zero (width of zero). Because the width of a real in
           * Icarus is 1 the string length will set the width of a real
           * displayed using %d. */
          if (width == -1) {
            width = (ld_zero == 1) ? 0 : vpi_get_dec_size(info->items[*idx]);
          }

          /* If the default buffer is too small make it big enough. */
          size = strlen(tbuf) + 1;
          if ((signed)size < (width+1)) size = width+1;
          if (size > ini_size) result = realloc(result, size*sizeof(char));

          if (ljust == 0) sprintf(result, "%*s", width, tbuf);
          else sprintf(result, "%-*s", width, tbuf);
          free(tbuf);
          size = strlen(result) + 1;
        }
      }
      break;

    case 'e':
    case 'E':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
      *idx += 1;
      if (*idx >= info->nitems) {
        vpi_printf("WARNING: %s:%d: missing argument for %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      } else {
        value.format = vpiRealVal;
        vpi_get_value(info->items[*idx], &value);
        if (value.format == vpiSuppressVal) {
          vpi_printf("WARNING: %s:%d: incompatible value for %s%s.\n",
                     info->filename, info->lineno, info->name, fmtb);
        } else {
          char *cp = fmtb;

          if (fmt == 'F') {
            while (*cp != 'F') cp++;
            *cp = 'f';
          }
          while (*cp != '>') cp++;
          *cp = '\0';

          /* If the default buffer is too small make it big enough.
           *
           * This should always give enough space. The maximum double
           * is approximately 1.8*10^308 this means we could need 310
           * characters plus the precision. We'll use 320 to give some
           * extra buffer space. The initial buffers size should work
           * for most cases, but to be safe we add the precision to
           * the maximum size (think %6.300f when passed 1.2*10^308). */
          size = width + 1;
          if (size < 320) size = 320;
          size += prec;
          if (size > ini_size) result = realloc(result, size*sizeof(char));
          sprintf(result, fmtb+1, value.value.real);
          size = strlen(result) + 1;
        }
      }
      break;

    /* This Verilog format specifier is not currently supported!
     * vpiCell and vpiLibrary need to be implemented first. */
    case 'l':
    case 'L':
      vpi_printf("WARNING: %s:%d: %%%c currently unsupported %s%s.\n",
                 info->filename, info->lineno, fmt, info->name, fmtb);
      break;

    case 'm':
    case 'M':
      if (plus != 0 || prec != -1) {
        vpi_printf("WARNING: %s:%d: invalid format %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      }
      /* If a width was not given, use a width of zero. */
      if (width == -1) width = 0;

      {
        char *cp = vpi_get_str(vpiFullName, info->scope);
        /* If the default buffer is too small, make it big enough. */
        size = strlen(cp) + 1;
        if ((signed)size < (width+1)) size = width+1;
        if (size > ini_size) result = realloc(result, size*sizeof(char));

        if (ljust == 0) sprintf(result, "%*s", width, cp);
        else sprintf(result, "%-*s", width, cp);
      }
      size = strlen(result) + 1;
      break;

    case 's':
    case 'S':
      /* Strings are not numeric and are not zero filled, so %08s => %8s. */
      *idx += 1;
      if (plus != 0 || prec != -1) {
        vpi_printf("WARNING: %s:%d: invalid format %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      }
      if (*idx >= info->nitems) {
        vpi_printf("WARNING: %s:%d: missing argument for %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      } else {
        value.format = vpiStringVal;
        vpi_get_value(info->items[*idx], &value);
        if (value.format == vpiSuppressVal) {
          vpi_printf("WARNING: %s:%d: incompatible value for %s%s.\n",
                     info->filename, info->lineno, info->name, fmtb);
        } else {
          if (width == -1) {
            /* If all we have is a leading zero then we want a zero width. */
            if (ld_zero == 1) width = 0;
            /* Otherwise if a width was not given, use the value width. */
            else width = (vpi_get(vpiSize, info->items[*idx])+7) / 8;
          }
          /* If the default buffer is too small make it big enough. */
          size = strlen(value.value.str) + 1;
          if ((signed)size < (width+1)) size = width+1;
          if (size > ini_size) result = realloc(result, size*sizeof(char));
          if (ljust == 0) sprintf(result, "%*s", width, value.value.str);
          else sprintf(result, "%-*s", width, value.value.str);
          size = strlen(result) + 1;
        }
      }
      break;

    case 't':
    case 'T':
      *idx += 1;
      if (plus != 0) {
        vpi_printf("WARNING: %s:%d: invalid format %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      }
      if (*idx >= info->nitems) {
        vpi_printf("WARNING: %s:%d: missing argument for %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      } else {
        PLI_INT32 type;

        /* Get the argument type and value. */
        type = vpi_get(vpiType, info->items[*idx]);
        if (((type == vpiConstant || type == vpiParameter) &&
             vpi_get(vpiConstType, info->items[*idx]) == vpiRealConst) ||
            type == vpiRealVar || (type == vpiSysFuncCall &&
             vpi_get(vpiFuncType, info->items[*idx]) == vpiRealFunc)) {
          value.format = vpiRealVal;
        } else {
          value.format = vpiDecStrVal;
        }
        vpi_get_value(info->items[*idx], &value);
        if (value.format == vpiSuppressVal) {
          vpi_printf("WARNING: %s:%d: incompatible value for %s%s.\n",
                     info->filename, info->lineno, info->name, fmtb);
        } else {
          char *tbuf;
          PLI_INT32 time_units = vpi_get(vpiTimeUnit, info->scope);
          unsigned swidth, free_flag = 0;
          unsigned suff_len = strlen(timeformat_info.suff);
          char *cp;

          /* The 512 (513-1 for EOL) is more than enough for any double
           * value (309 digits plus a decimal point maximum). Because of
           * scaling this could be larger. For decimal values you can
           * have an arbitrary value so you can overflow the buffer, but
           * for now we will assume the user will use this as intended
           * (pass a time variable or the result of a time function). */
          tbuf = malloc((513+suff_len)*sizeof(char));
          if (prec == -1) prec = timeformat_info.prec;
          if (value.format == vpiRealVal) {
            get_time_real(tbuf, value.value.real, prec, time_units);
          } else {
            get_time(tbuf, value.value.str, prec, time_units);
          }
          cp = tbuf;
          swidth = strlen(tbuf);

          if (ld_zero == 1) {
            /* No leading zeros are created by this conversion so just make
             * the width 0 for this case. */
            if (width == -1) width = 0;
            /* Pad with leading zeros. */
            else if (ljust == 0 && (signed)swidth < width) {
              unsigned pad = (unsigned)width - swidth;
              cp = malloc((width+1)*sizeof(char));
              memset(cp, '0', pad);
              strcpy(cp+pad, tbuf);
              free_flag = 1;
            }
          }
          if (width == -1) width = timeformat_info.width;

          /* If the default buffer is too small make it big enough. */
          size = strlen(tbuf) + 1;
          if ((signed)size < (width+1)) size = width+1;
          if (size > ini_size) result = realloc(result, size*sizeof(char));

          if (ljust == 0) sprintf(result, "%*s", width, cp);
          else sprintf(result, "%-*s", width, cp);
          if (free_flag) free(cp);
          free(tbuf);
          size = strlen(result) + 1;
        }
      }
      break;

    case 'u':
    case 'U':
      *idx += 1;
      if (ljust != 0  || plus != 0 || ld_zero != 0 || width != -1 ||
          prec != -1) {
        vpi_printf("WARNING: %s:%d: invalid format %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      }
      if (*idx >= info->nitems) {
        vpi_printf("WARNING: %s:%d: missing argument for %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      } else {
        value.format = vpiVectorVal;
        vpi_get_value(info->items[*idx], &value);
        if (value.format == vpiSuppressVal) {
          vpi_printf("WARNING: %s:%d: incompatible value for %s%s.\n",
                     info->filename, info->lineno, info->name, fmtb);
        } else {
          PLI_INT32 veclen, word, byte, bits;
          char *cp;

          veclen = (vpi_get(vpiSize, info->items[*idx])+31)/32;
          size = veclen * 4 + 1;
          /* If the default buffer is too small, make it big enough. */
          if (size > ini_size) result = realloc(result, size*sizeof(char));
          cp = result;
          for (word = 0; word < veclen; word += 1) {
            bits = value.value.vector[word].aval &
                   ~value.value.vector[word].bval;
#ifdef WORDS_BIGENDIAN
            for (byte = 3; byte >= 0; byte -= 1) {
#else
            for (byte = 0; byte <= 3; byte += 1) {
#endif
              *cp = (bits >> byte*8) & 0xff;
              cp += 1;
            }
          }
          *cp = '\0';
        }
      }
      /* size is defined above! We can't use strlen here since this can
       * be a binary string (can contain NULLs). */
      break;

    case 'v':
    case 'V':
      *idx += 1;
      if (plus != 0 || prec != -1) {
        vpi_printf("WARNING: %s:%d: invalid format %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      }
      if (*idx >= info->nitems) {
        vpi_printf("WARNING: %s:%d: missing argument for %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      } else {
        value.format = vpiStrengthVal;
        vpi_get_value(info->items[*idx], &value);
        if (value.format == vpiSuppressVal) {
          vpi_printf("WARNING: %s:%d: incompatible value for %s%s.\n",
                     info->filename, info->lineno, info->name, fmtb);
        } else {
          char tbuf[4], *rbuf;
          PLI_INT32 nbits;
          int bit;

          /* If a width was not given use a width of zero. */
          if (width == -1) width = 0;
          nbits = vpi_get(vpiSize, info->items[*idx]);
          /* This is 4 chars for all but the last bit (strength + "_")
           * which only needs three chars (strength), but then you need
           * space for the EOS '\0', so it is just number of bits * 4. */
          size = nbits*4;
          rbuf = malloc(size*sizeof(char));
          if ((signed)size < (width+1)) size = width+1;
          if (size > ini_size) result = realloc(result, size*sizeof(char));
          strcpy(rbuf, "");
          for (bit = nbits-1; bit >= 0; bit -= 1) {
            vpip_format_strength(tbuf, &value, bit);
            strcat(rbuf, tbuf);
	    if (bit > 0) strcat(rbuf, "_");
          }
          if (ljust == 0) sprintf(result, "%*s", width, rbuf);
          else sprintf(result, "%-*s", width, rbuf);
          free(rbuf);
          size = strlen(result) + 1;
        }
      }
      break;

    case 'z':
    case 'Z':
      *idx += 1;
      size = strlen(result) + 1; /* fallback value if errors */
      if (ljust != 0  || plus != 0 || ld_zero != 0 || width != -1 ||
          prec != -1) {
        vpi_printf("WARNING: %s:%d: invalid format %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      }
      if (*idx >= info->nitems) {
        vpi_printf("WARNING: %s:%d: missing argument for %s%s.\n",
                   info->filename, info->lineno, info->name, fmtb);
      } else {
        value.format = vpiVectorVal;
        vpi_get_value(info->items[*idx], &value);
        if (value.format == vpiSuppressVal) {
          vpi_printf("WARNING: %s:%d: incompatible value for %s%s.\n",
                     info->filename, info->lineno, info->name, fmtb);
        } else {
          PLI_INT32 veclen, word, elem, bits, byte;
          char *cp;

          veclen = (vpi_get(vpiSize, info->items[*idx])+31)/32;
          size = 2 * veclen * 4 + 1;
          /* If the default buffer is too small, make it big enough. */
          if (size > ini_size) result = realloc(result, size*sizeof(char));
          cp = result;
          for (word = 0; word < veclen; word += 1) {
            /* Write the aval followed by the bval in endian order. */
            for (elem = 0; elem < 2; elem += 1) {
              bits = *(&value.value.vector[word].aval+elem);
#ifdef WORDS_BIGENDIAN
              for (byte = 3; byte >= 0; byte -= 1) {
#else
              for (byte = 0; byte <= 3; byte += 1) {
#endif
                *cp = (bits >> byte*8) & 0xff;
                cp += 1;
              }
            }
          }
          *cp = '\0';
        }
      }
      /* size is defined above! We can't use strlen here since this can
       * be a binary string (can contain NULLs). */
      break;

    default:
      vpi_printf("WARNING: %s:%d: unknown format %s%s.\n",
                 info->filename, info->lineno, info->name, fmtb);
      size = strlen(result) + 1;
      break;
  }
  free(fmtb);
  /* We can't use strdup here since %u and %z can insert NULL
   * characters into the stream. */
  *rtn = malloc(size*sizeof(char));
  memcpy(*rtn, result, size);
  free(result);
  return size - 1;
}

/* We can't use the normal str functions on the return value since
 * %u and %z can insert NULL characters into the stream. */
static unsigned int get_format(char **rtn, char *fmt,
                               const struct strobe_cb_info *info, unsigned int *idx)
{
  char *cp = fmt;
  unsigned int size;

  *rtn = strdup("");
  size = 1;
  while (*cp) {
    size_t cnt = strcspn(cp, "%");

    if (cnt > 0) {
      *rtn = realloc(*rtn, (size+cnt)*sizeof(char));
      memcpy(*rtn+size-1, cp, cnt);
      size += cnt;
      cp += cnt;
    } else {
      int ljust = 0, plus = 0, ld_zero = 0, width = -1, prec = -1;
      char *result;

      cp += 1;
      while ((*cp == '-') || (*cp == '+')) {
        if (*cp == '-') ljust = 1;
        else plus = 1;
        cp += 1;
      }
      if (*cp == '0') {
        ld_zero = 1;
        cp += 1;
      }
      if (isdigit((int)*cp)) width = strtoul(cp, &cp, 10);
      if (*cp == '.') {
        cp += 1;
        prec = strtoul(cp, &cp, 10);
      }
      cnt = get_format_char(&result, ljust, plus, ld_zero, width, prec, *cp,
                            info, idx);
      *rtn = realloc(*rtn, (size+cnt)*sizeof(char));
      memcpy(*rtn+size-1, result, cnt);
      free(result);
      size += cnt;
      if (*cp) cp += 1;
    }
  }
  *(*rtn+size-1) = '\0';
  return size - 1;
}

static unsigned int get_numeric(char **rtn, const struct strobe_cb_info *info,
                                vpiHandle item)
{
  int size, min;
  s_vpi_value val;

  val.format = info->default_format;
  vpi_get_value(item, &val);

  switch(info->default_format){
    case vpiDecStrVal:
      size = vpi_get_dec_size(item);
	/* -1 can be represented as a one bit signed value. This returns	
	 * a size of 1 which is too small for the -1 string value so make
	 * the string width the minimum display width. */
      min = strlen(val.value.str);
      if (size < min) size = min;
      *rtn = malloc((size+1)*sizeof(char));
      sprintf(*rtn, "%*s", size, val.value.str);
      break;
    default:
      *rtn = strdup(val.value.str);
  }

  return strlen(*rtn);
}

/* In many places we can't use the normal str functions since %u and %z
 * can insert NULL characters into the stream. */
static char *get_display(unsigned int *rtnsz, const struct strobe_cb_info *info)
{
  char *result, *fmt, *rtn, *func_name;
  const char *cresult;
  s_vpi_value value;
  unsigned int idx, size, width;
  char buf[256];

  rtn = strdup("");
  size = 1;
  for  (idx = 0; idx < info->nitems; idx += 1) {
    vpiHandle item = info->items[idx];

    switch (vpi_get(vpiType, item)) {

      case vpiConstant:
      case vpiParameter:
        if (vpi_get(vpiConstType, item) == vpiStringConst) {
          value.format = vpiStringVal;
          vpi_get_value(item, &value);
          fmt = strdup(value.value.str);
          width = get_format(&result, fmt, info, &idx);
          free(fmt);
        } else if (vpi_get(vpiConstType, item) == vpiRealConst) {
          value.format = vpiRealVal;
          vpi_get_value(item, &value);
          sprintf(buf, "%#g", value.value.real);
          result = strdup(buf);
          width = strlen(result);
        } else {
          width = get_numeric(&result, info, item);
        }
        rtn = realloc(rtn, (size+width)*sizeof(char));
        memcpy(rtn+size-1, result, width);
        free(result);
        break;

      case vpiNet:
      case vpiReg:
      case vpiIntegerVar:
      case vpiMemoryWord:
      case vpiPartSelect:
        width = get_numeric(&result, info, item);
        rtn = realloc(rtn, (size+width)*sizeof(char));
        memcpy(rtn+size-1, result, width);
        free(result);
        break;

      /* It appears that this is not currently used! A time variable is
         passed as an integer and processed above. Hence this code has
         only been visually checked. */
      case vpiTimeVar:
        value.format = vpiDecStrVal;
        vpi_get_value(item, &value);
        get_time(buf, value.value.str, timeformat_info.prec,
                 vpi_get(vpiTimeUnit, info->scope));
        width = strlen(buf);
        if (width  < timeformat_info.width) width = timeformat_info.width;
        rtn = realloc(rtn, (size+width)*sizeof(char));
        sprintf(rtn+size-1, "%*s", width, buf);
        break;

      /* Realtime variables are also processed here. */
      case vpiRealVar:
        value.format = vpiRealVal;
        vpi_get_value(item, &value);
        sprintf(buf, "%#g", value.value.real);
        width = strlen(buf);
        rtn = realloc(rtn, (size+width)*sizeof(char));
        memcpy(rtn+size-1, buf, width);
        break;

      case vpiSysFuncCall:
        func_name = vpi_get_str(vpiName, item);
        if (strcmp(func_name, "$time") == 0) {
          value.format = vpiDecStrVal;
          vpi_get_value(item, &value);
          width = strlen(value.value.str);
          if (width  < 20) width = 20;
          rtn = realloc(rtn, (size+width)*sizeof(char));
          sprintf(rtn+size-1, "%*s", width, value.value.str);

        } else if (strcmp(func_name, "$stime") == 0) {
          value.format = vpiDecStrVal;
          vpi_get_value(item, &value);
          width = strlen(value.value.str);
          if (width  < 10) width = 10;
          rtn = realloc(rtn, (size+width)*sizeof(char));
          sprintf(rtn+size-1, "%*s", width, value.value.str);

        } else if (strcmp(func_name, "$simtime") == 0) {
          value.format = vpiDecStrVal;
          vpi_get_value(item, &value);
          width = strlen(value.value.str);
          if (width  < 20) width = 20;
          rtn = realloc(rtn, (size+width)*sizeof(char));
          sprintf(rtn+size-1, "%*s", width, value.value.str);

        } else if (strcmp(func_name, "$realtime") == 0) {
          /* Use the local scope precision. */
          int use_prec = vpi_get(vpiTimeUnit, info->scope) -
                         vpi_get(vpiTimePrecision, info->scope);
          assert(use_prec >= 0);
          value.format = vpiRealVal;
          vpi_get_value(item, &value);
          sprintf(buf, "%.*f", use_prec, value.value.real);
          width = strlen(buf);
          rtn = realloc(rtn, (size+width)*sizeof(char));
          sprintf(rtn+size-1, "%*s", width, buf);

        } else {
          vpi_printf("WARNING: %s:%d: %s does not support %s as an argument!\n",
                     info->filename, info->lineno, info->name, func_name);
          strcpy(buf, "<?>");
          width = strlen(buf);
          rtn = realloc(rtn, (size+width)*sizeof(char));
          memcpy(rtn+size-1, buf, width);
        }
        break;

      default:
        vpi_printf("WARNING: %s:%d: unknown argument type (%s) given to %s!\n",
                   info->filename, info->lineno, vpi_get_str(vpiType, item),
                   info->name);
        cresult = "<?>";
        width = strlen(cresult);
        rtn = realloc(rtn, (size+width)*sizeof(char));
        memcpy(rtn+size-1, cresult, width);
        break;
    }
    size += width;
  }
  rtn[size-1] = '\0';
  *rtnsz = size - 1;
  return rtn;
}

static int sys_check_args(vpiHandle callh, vpiHandle argv, const PLI_BYTE8*name,
                          int no_auto, int is_monitor)
{
      vpiHandle arg;
      int ret = 0;

        /* If there are no arguments, just return. */
      if (argv == 0) return ret;

      for (arg = vpi_scan(argv); arg; arg = vpi_scan(argv)) {
            if (no_auto && vpi_get(vpiAutomatic, arg)) {
                  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
                             (int)vpi_get(vpiLineNo, callh));
                  vpi_printf("%s argument \"%s\" is an automatic variable.\n",
                             name, vpi_get_str(vpiName, arg));
                  ret = 1;
	    }

	    switch (vpi_get(vpiType, arg)) {
	      case vpiMemoryWord:
	      case vpiPartSelect:
		  if (is_monitor && vpi_get(vpiConstantSelect, arg) == 0) {
			vpi_printf("SORRY: %s:%d: ",
			           vpi_get_str(vpiFile, callh),
			           (int)vpi_get(vpiLineNo, callh));
			vpi_printf("%s must have a constant %s select.\n",
			           name, vpi_get_str(vpiType, arg));
			ret = 1;
		  }

	      case vpiConstant:
	      case vpiParameter:
	      case vpiNet:
	      case vpiReg:
	      case vpiIntegerVar:
	      case vpiTimeVar:
	      case vpiRealVar:
	      case vpiSysFuncCall:
		  break;

	      default:
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s does not support argument type (%s).\n", name,
		             vpi_get_str(vpiType, arg));
		  ret = 1;
		  break;
	    }
      }

      return ret;
}

/* Common compiletf routine. */
static PLI_INT32 sys_common_compiletf(PLI_BYTE8*name, int no_auto,
                                      int is_monitor)
{
      vpiHandle callh, argv;

      callh = vpi_handle(vpiSysTfCall, 0);
      argv = vpi_iterate(vpiArgument, callh);

      if(name[1] == 'f') {
	      /* Check that there is a fd/mcd and that it is numeric. */
	    if (argv == 0) {
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s requires at least a file descriptor/MCD.\n",
		             name);
		  vpi_control(vpiFinish, 1);
		  return 0;
	    }

	    if (! is_numeric_obj(vpi_scan(argv))) {
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s's file descriptor/MCD must be numeric.\n",
		             name);
		  vpi_control(vpiFinish, 1);
	    }
      }

      if (sys_check_args(callh, argv, name, no_auto, is_monitor)) {
	    vpi_control(vpiFinish, 1);
      }
      return 0;
}

/* Check the $display, $write, $fdisplay and $fwrite based tasks. */
static PLI_INT32 sys_display_compiletf(PLI_BYTE8*name)
{
	/* These tasks can have automatic variables and are not monitor. */
      return sys_common_compiletf(name, 0, 0);
}

/* This implements the $display/$fdisplay and the $write/$fwrite based tasks. */
static PLI_INT32 sys_display_calltf(PLI_BYTE8 *name)
{
      vpiHandle callh, argv, scope;
      struct strobe_cb_info info;
      char* result;
      unsigned int size, location=0;
      PLI_UINT32 fd_mcd;

      callh = vpi_handle(vpiSysTfCall, 0);
      argv = vpi_iterate(vpiArgument, callh);

	/* Get the file/MC descriptor and verify it is valid. */
      if(name[1] == 'f') {
	      errno = 0;
	      vpiHandle arg = vpi_scan(argv);
	      s_vpi_value val;
	      val.format = vpiIntVal;
	      vpi_get_value(arg, &val);
	      fd_mcd = val.value.integer;

		/* If the MCD is zero we have nothing to do so just return. */
	      if (fd_mcd == 0)  {
		    vpi_free_object(argv);
		    return 0;
	      }

	      if ((! IS_MCD(fd_mcd) && vpi_get_file(fd_mcd) == NULL) ||
	          ( IS_MCD(fd_mcd) && my_mcd_printf(fd_mcd, "") == EOF)) {
		    vpi_printf("WARNING: %s:%d: ", vpi_get_str(vpiFile, callh),
		               (int)vpi_get(vpiLineNo, callh));
		    vpi_printf("invalid file descriptor/MCD (0x%x) given "
		               "to %s.\n", (unsigned int)fd_mcd, name);
		    errno = EBADF;
		    vpi_free_object(argv);
		    return 0;
	      }
      } else {
	      fd_mcd = 1;
      }

      scope = vpi_handle(vpiScope, callh);
      assert(scope);
	/* We could use vpi_get_str(vpiName, callh) to get the task name,
	 * but name is already defined. */
      info.name = name;
      info.filename = strdup(vpi_get_str(vpiFile, callh));
      info.lineno = (int)vpi_get(vpiLineNo, callh);
      info.default_format = get_default_format(name);
      info.scope = scope;
      array_from_iterator(&info, argv);

	/* Because %u and %z may put embedded NULL characters into the
	 * returned string strlen() may not match the real size! */
      result = get_display(&size, &info);
      while (location < size) {
	    if (result[location] == '\0') {
		  my_mcd_printf(fd_mcd, "%c", '\0');
		  location += 1;
	    } else {
		  my_mcd_printf(fd_mcd, "%s", &result[location]);
		  location += strlen(&result[location]);
	    }
      }
      if ((strncmp(name,"$display",8) == 0) ||
          (strncmp(name,"$fdisplay",9) == 0)) my_mcd_printf(fd_mcd, "\n");

      free(info.filename);
      free(info.items);
      free(result);
      return 0;
}

/*
 * The strobe implementation takes the parameter handles that are
 * passed to the calltf and puts them in to an array for safe
 * keeping. That array (and other bookkeeping) is passed, via the
 * struct_cb_info object, to the REadOnlySych function strobe_cb,
 * where it is used to perform the actual formatting and printing.
 */
static PLI_INT32 strobe_cb(p_cb_data cb)
{
      struct strobe_cb_info*info = (struct strobe_cb_info*)cb->user_data;

	/* We really need to cancel any $fstrobe() calls for a file when it
	 * is closed, but for now we will just skip processing the result.
	 * Which has the same basic effect. */
      if ((! IS_MCD(info->fd_mcd) && vpi_get_file(info->fd_mcd) != NULL) ||
          ( IS_MCD(info->fd_mcd) && my_mcd_printf(info->fd_mcd, "") != EOF)) {
	    char* result = NULL;
	    unsigned int size, location=0;
	      /* Because %u and %z may put embedded NULL characters into the
	       * returned string strlen() may not match the real size! */
	    result = get_display(&size, info);
	    while (location < size) {
		  if (result[location] == '\0') {
			my_mcd_printf(info->fd_mcd, "%c", '\0');
			location += 1;
		  } else {
			my_mcd_printf(info->fd_mcd, "%s", &result[location]);
			location += strlen(&result[location]);
		  }
	    }
	    my_mcd_printf(info->fd_mcd, "\n");
	    free(result);
      }

      free(info->filename);
      free(info->items);
      free(info);
      return 0;
}

/* Check both the $strobe and $fstrobe based tasks. */
static PLI_INT32 sys_strobe_compiletf(PLI_BYTE8 *name)
{
	/* These tasks can not have automatic variables and are not monitor. */
      return sys_common_compiletf(name, 1, 0);
}

/* This implements both the $strobe and $fstrobe based tasks. */
static PLI_INT32 sys_strobe_calltf(PLI_BYTE8*name)
{
      vpiHandle callh, argv, scope;
      struct t_cb_data cb;
      struct t_vpi_time timerec;
      struct strobe_cb_info*info;
      PLI_UINT32 fd_mcd;

      callh = vpi_handle(vpiSysTfCall, 0);
      argv = vpi_iterate(vpiArgument, callh);

	/* Get the file/MC descriptor and verify it is valid. */
      if(name[1] == 'f') {
	      errno = 0;
	      vpiHandle arg = vpi_scan(argv);
	      s_vpi_value val;
	      val.format = vpiIntVal;
	      vpi_get_value(arg, &val);
	      fd_mcd = val.value.integer;

		/* If the MCD is zero we have nothing to do so just return. */
	      if (fd_mcd == 0)  {
		    vpi_free_object(argv);
		    return 0;
	      }

	      if ((! IS_MCD(fd_mcd) && vpi_get_file(fd_mcd) == NULL) ||
	          ( IS_MCD(fd_mcd) && my_mcd_printf(fd_mcd, "") == EOF))  {
		    vpi_printf("WARNING: %s:%d: ", vpi_get_str(vpiFile, callh),
		               (int)vpi_get(vpiLineNo, callh));
		    vpi_printf("invalid file descriptor/MCD (0x%x) given "
		               "to %s.\n", (unsigned int)fd_mcd, name);
		    errno = EBADF;
		    vpi_free_object(argv);
		    return 0;
	      }
      } else {
	      fd_mcd = 1;
      }

      scope = vpi_handle(vpiScope, callh);
      assert(scope);

      info = calloc(1, sizeof(struct strobe_cb_info));
      info->fd_mcd = fd_mcd;
	/* We could use vpi_get_str(vpiName, callh) to get the task name,
	 * but name is already defined. */
      info->name = name;
      info->filename = strdup(vpi_get_str(vpiFile, callh));
      info->lineno = (int)vpi_get(vpiLineNo, callh);
      info->default_format = get_default_format(name);
      info->scope= scope;
      array_from_iterator(info, argv);

      timerec.type = vpiSimTime;
      timerec.low = 0;
      timerec.high = 0;

      cb.reason = cbReadOnlySynch;
      cb.cb_rtn = strobe_cb;
      cb.time = &timerec;
      cb.obj = 0;
      cb.value = 0;
      cb.user_data = (char*)info;
      vpi_register_cb(&cb);
      return 0;
}

/*
 * The $monitor system task works by managing these static variables,
 * and the cbValueChange callbacks associated with registers and
 * nets. Note that it is proper to keep the state in static variables
 * because there can only be one monitor at a time pending (even
 * though that monitor may be watching many variables).
 */

static struct strobe_cb_info monitor_info = { 0, 0, 0, 0, 0, 0, 0, 0 };
static vpiHandle *monitor_callbacks = 0;
static int monitor_scheduled = 0;
static int monitor_enabled = 1;

static PLI_INT32 monitor_cb_2(p_cb_data cb)
{
      char* result;
      unsigned int size, location=0;

	/* Because %u and %z may put embedded NULL characters into the
	 * returned string strlen() may not match the real size! */
      result = get_display(&size, &monitor_info);
      while (location < size) {
	    if (result[location] == '\0') {
		  my_mcd_printf(monitor_info.fd_mcd, "%c", '\0');
		  location += 1;
	    } else {
		  my_mcd_printf(monitor_info.fd_mcd, "%s", &result[location]);
		  location += strlen(&result[location]);
	    }
      }
      my_mcd_printf(monitor_info.fd_mcd, "\n");
      monitor_scheduled = 0;
      free(result);
      return 0;
}

/*
 * The monitor_cb_1 callback is called when an event occurs somewhere
 * in the simulation. All this function does is schedule the actual
 * display to occur in a ReadOnlySync callback. The monitor_scheduled
 * flag is used to allow only one monitor strobe to be scheduled.
 */
static PLI_INT32 monitor_cb_1(p_cb_data cause)
{
      struct t_cb_data cb;
      struct t_vpi_time timerec;

      if (monitor_enabled == 0) return 0;
      if (monitor_scheduled) return 0;

	/* This this action caused the first trigger, then schedule
	   the monitor to happen at the end of the time slice and mark
	   it as scheduled. */
      monitor_scheduled += 1;
      timerec.type = vpiSimTime;
      timerec.low = 0;
      timerec.high = 0;

      cb.reason = cbReadOnlySynch;
      cb.cb_rtn = monitor_cb_2;
      cb.time = &timerec;
      cb.obj = 0;
      cb.value = 0;
      vpi_register_cb(&cb);

      return 0;
}

static PLI_INT32 sys_monitor_compiletf(PLI_BYTE8 *name)
{
      vpiHandle callh = vpi_handle(vpiSysTfCall, 0);
      vpiHandle argv = vpi_iterate(vpiArgument, callh);

      if (sys_check_args(callh, argv, name, 1, 1)) vpi_control(vpiFinish, 1);
      return 0;
}

static PLI_INT32 sys_monitor_calltf(PLI_BYTE8*name)
{
      vpiHandle callh, argv, scope;
      unsigned idx;
      struct t_cb_data cb;
      struct t_vpi_time timerec;

      callh = vpi_handle(vpiSysTfCall, 0);
      argv = vpi_iterate(vpiArgument, callh);

	/* If there was a previous $monitor, then remove the callbacks
	   related to it. */
      if (monitor_callbacks) {
	    for (idx = 0 ;  idx < monitor_info.nitems ;  idx += 1)
		  if (monitor_callbacks[idx])
			vpi_remove_cb(monitor_callbacks[idx]);

	    free(monitor_callbacks);
	    monitor_callbacks = 0;

	    free(monitor_info.filename);
	    free(monitor_info.items);
	    monitor_info.items = 0;
	    monitor_info.nitems = 0;
	    monitor_info.name = 0;
      }

      scope = vpi_handle(vpiScope, callh);
      assert(scope);
	/* Make an array of handles from the argument list. */
      array_from_iterator(&monitor_info, argv);
      monitor_info.name = name;
      monitor_info.filename = strdup(vpi_get_str(vpiFile, callh));
      monitor_info.lineno = (int)vpi_get(vpiLineNo, callh);
      monitor_info.default_format = get_default_format(name);
      monitor_info.scope = scope;
      monitor_info.fd_mcd = 1;

	/* Attach callbacks to all the parameters that might change. */
      monitor_callbacks = calloc(monitor_info.nitems, sizeof(vpiHandle));

      timerec.type = vpiSuppressTime;
      cb.reason = cbValueChange;
      cb.cb_rtn = monitor_cb_1;
      cb.time = &timerec;
      cb.value = NULL;
      for (idx = 0 ;  idx < monitor_info.nitems ;  idx += 1) {

	    switch (vpi_get(vpiType, monitor_info.items[idx])) {
		case vpiMemoryWord:
		  /*
		   * We only support constant selections. Make this
		   * better when we add a real compiletf routine.
		   */
		  assert(vpi_get(vpiConstantSelect, monitor_info.items[idx]));
		case vpiNet:
		case vpiReg:
		case vpiIntegerVar:
		case vpiRealVar:
		case vpiPartSelect:
		    /* Monitoring reg and net values involves setting
		       a callback for value changes. Pass the storage
		       pointer for the callback itself as user_data so
		       that the callback can refresh itself. */
		  cb.user_data = (char*)(monitor_callbacks+idx);
		  cb.obj = monitor_info.items[idx];
		  monitor_callbacks[idx] = vpi_register_cb(&cb);
		  break;

	    }
      }

	/* When the $monitor is called, it schedules a first display
	   for the end of the current time, like a $strobe. */
      monitor_cb_1(0);

      return 0;
}

static PLI_INT32 sys_monitoron_calltf(PLI_BYTE8*name)
{
      monitor_enabled = 1;
      monitor_cb_1(0);
      return 0;
}

static PLI_INT32 sys_monitoroff_calltf(PLI_BYTE8*name)
{
      monitor_enabled = 0;
      return 0;
}

static PLI_INT32 sys_swrite_compiletf(PLI_BYTE8 *name)
{
  vpiHandle callh = vpi_handle(vpiSysTfCall, 0);
  vpiHandle argv = vpi_iterate(vpiArgument, callh);
  vpiHandle reg;

  /* Check that there are arguments. */
  if (argv == 0) {
    vpi_printf("ERROR:%s:%d: ", vpi_get_str(vpiFile, callh),
               (int)vpi_get(vpiLineNo, callh));
    vpi_printf("%s requires at least one argument.\n", name);
    vpi_control(vpiFinish, 1);
    return 0;
  }

  /* The first argument must be a register. */
  reg = vpi_scan(argv);  /* This should never be zero. */
  if (vpi_get(vpiType, reg) != vpiReg) {
    vpi_printf("ERROR:%s:%d: ", vpi_get_str(vpiFile, callh),
               (int)vpi_get(vpiLineNo, callh));
    vpi_printf("%s's first argument must be a register.\n", name);
    vpi_control(vpiFinish, 1);
    return 0;
  }

  if (sys_check_args(callh, argv, name, 0, 0)) vpi_control(vpiFinish, 1);
  return 0;
}

static PLI_INT32 sys_swrite_calltf(PLI_BYTE8 *name)
{
  vpiHandle callh, argv, reg, scope;
  struct strobe_cb_info info;
  s_vpi_value val;
  unsigned int size;

  callh = vpi_handle(vpiSysTfCall, 0);
  argv = vpi_iterate(vpiArgument, callh);
  reg = vpi_scan(argv);

  scope = vpi_handle(vpiScope, callh);
  assert(scope);
  /* We could use vpi_get_str(vpiName, callh) to get the task name, but
   * name is already defined. */
  info.name = name;
  info.filename = strdup(vpi_get_str(vpiFile, callh));
  info.lineno = (int)vpi_get(vpiLineNo, callh);
  info.default_format = get_default_format(name);
  info.scope = scope;
  array_from_iterator(&info, argv);

  /* Because %u and %z may put embedded NULL characters into the returned
   * string strlen() may not match the real size! */
  val.value.str = get_display(&size, &info);
  val.format = vpiStringVal;
  vpi_put_value(reg, &val, 0, vpiNoDelay);
  if (size != strlen(val.value.str)) {
    vpi_printf("WARNING: %s:%d: %s returned a value with an embedded NULL "
               "(see %%u/%%z).\n", info.filename, info.lineno, name);
  }

  free(val.value.str);
  free(info.filename);
  free(info.items);
  return 0;
}

static PLI_INT32 sys_sformat_compiletf(PLI_BYTE8 *name)
{
  vpiHandle callh = vpi_handle(vpiSysTfCall, 0);
  vpiHandle argv = vpi_iterate(vpiArgument, callh);
  vpiHandle arg;
  PLI_INT32 type;

  /* Check that there are arguments. */
  if (argv == 0) {
    vpi_printf("ERROR:%s:%d: ", vpi_get_str(vpiFile, callh),
               (int)vpi_get(vpiLineNo, callh));
    vpi_printf("%s requires at least two argument.\n", name);
    vpi_control(vpiFinish, 1);
    return 0;
  }

  /* The first argument must be a register. */
  arg = vpi_scan(argv);  /* This should never be zero. */
  if (vpi_get(vpiType, arg) != vpiReg) {
    vpi_printf("ERROR:%s:%d: ", vpi_get_str(vpiFile, callh),
               (int)vpi_get(vpiLineNo, callh));
    vpi_printf("%s's first argument must be a register.\n", name);
    vpi_control(vpiFinish, 1);
    return 0;
  }

  /* The second argument must be a string or a register. */
  arg = vpi_scan(argv);
  if (arg == 0) {
    vpi_printf("ERROR:%s:%d: ", vpi_get_str(vpiFile, callh),
               (int)vpi_get(vpiLineNo, callh));
    vpi_printf("%s requires at least two argument.\n", name);
    vpi_control(vpiFinish, 1);
    return 0;
  }
  type = vpi_get(vpiType, arg);
  if (((type != vpiConstant && type != vpiParameter) ||
      vpi_get(vpiConstType, arg) != vpiStringConst) && type != vpiReg) {
    vpi_printf("ERROR:%s:%d: ", vpi_get_str(vpiFile, callh),
               (int)vpi_get(vpiLineNo, callh));
    vpi_printf("%s's second argument must be a string or a register.\n", name);
    vpi_control(vpiFinish, 1);
    return 0;
  }

  if (sys_check_args(callh, argv, name, 0, 0)) vpi_control(vpiFinish, 1);
  return 0;
}

static PLI_INT32 sys_sformat_calltf(PLI_BYTE8 *name)
{
  vpiHandle callh, argv, reg, scope;
  struct strobe_cb_info info;
  s_vpi_value val;
  char *result, *fmt;
  unsigned int idx, size;

  callh = vpi_handle(vpiSysTfCall, 0);
  argv = vpi_iterate(vpiArgument, callh);
  reg = vpi_scan(argv);
  val.format = vpiStringVal;
  vpi_get_value(vpi_scan(argv), &val);
  fmt = strdup(val.value.str);

  scope = vpi_handle(vpiScope, callh);
  assert(scope);
  /* We could use vpi_get_str(vpiName, callh) to get the task name, but
   * name is already defined. */
  info.name = name;
  info.filename = strdup(vpi_get_str(vpiFile, callh));
  info.lineno = (int)vpi_get(vpiLineNo, callh);
  info.default_format = get_default_format(name);
  info.scope = scope;
  array_from_iterator(&info, argv);
  idx = -1;
  size = get_format(&result, fmt, &info, &idx);
  free(fmt);

  if (idx+1< info.nitems) {
    vpi_printf("WARNING: %s:%d: %s has %d extra argument(s).\n",
               info.filename, info.lineno,  name,
               info.nitems-idx-1);
  }

  val.value.str = result;
  val.format = vpiStringVal;
  vpi_put_value(reg, &val, 0, vpiNoDelay);
  if (size != strlen(val.value.str)) {
    vpi_printf("WARNING: %s:%d: %s returned a value with an embedded NULL "
               "(see %%u/%%z).\n", info.filename, info.lineno, name);
  }

  free(val.value.str);
  free(info.filename);
  free(info.items);
  return 0;
}

static PLI_INT32 sys_end_of_compile(p_cb_data cb_data)
{
	/* The default timeformat prints times in unit of simulation
	   precision. */
      free(timeformat_info.suff);
      timeformat_info.suff  = strdup("");
      timeformat_info.units = vpi_get(vpiTimePrecision, 0);
      timeformat_info.prec  = 0;
      timeformat_info.width = 20;
      return 0;
}

static PLI_INT32 sys_timeformat_compiletf(PLI_BYTE8*name)
{
      vpiHandle callh   = vpi_handle(vpiSysTfCall, 0);
      vpiHandle argv  = vpi_iterate(vpiArgument, callh);

      if (argv) {
	    vpiHandle arg;

	      /* Check that the unit argument is numeric. */
	    if (! is_numeric_obj(vpi_scan(argv))) {
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s's units argument must be numeric.\n", name);
		  vpi_control(vpiFinish, 1);
	    }

	      /* Check that the precision argument is given and is numeric. */
	    arg = vpi_scan(argv);
	    if (! arg) {
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s requires zero or four arguments.\n", name);
		  vpi_control(vpiFinish, 1);
		  return 0;
	    }

	    if (! is_numeric_obj(arg)) {
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s's precision argument must be numeric.\n",
		             name);
		  vpi_control(vpiFinish, 1);
	    }

	      /* Check that the suffix argument is given and is a string. */
	    arg = vpi_scan(argv);
	    if (! arg) {
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s requires zero or four arguments.\n", name);
		  vpi_control(vpiFinish, 1);
		  return 0;
	    }

	    if (! is_string_obj(arg)) {
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s's suffix argument must be a string.\n", name);
		  vpi_control(vpiFinish, 1);
	    }

	      /* Check that the min. width argument is given and is numeric. */
	    arg = vpi_scan(argv);
	    if (! arg) {
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s requires zero or four arguments.\n", name);
		  vpi_control(vpiFinish, 1);
		  return 0;
	    }

	    if (! is_numeric_obj(arg)) {
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s's minimum width argument must be numeric.\n",
		             name);
		  vpi_control(vpiFinish, 1);
	    }

	      /* Make sure there are no extra arguments. */
	    check_for_extra_args(argv, callh, name, "four arguments", 0);
      }

      return 0;
}

static PLI_INT32 sys_timeformat_calltf(PLI_BYTE8*xx)
{
      s_vpi_value value;
      vpiHandle sys   = vpi_handle(vpiSysTfCall, 0);
      vpiHandle argv  = vpi_iterate(vpiArgument, sys);

      if (argv) {
            vpiHandle units = vpi_scan(argv);
            vpiHandle prec  = vpi_scan(argv);
            vpiHandle suff  = vpi_scan(argv);
            vpiHandle wid   = vpi_scan(argv);

            vpi_free_object(argv);

            value.format = vpiIntVal;
            vpi_get_value(units, &value);
            timeformat_info.units = value.value.integer;

            value.format = vpiIntVal;
            vpi_get_value(prec, &value);
            timeformat_info.prec = value.value.integer;

            value.format = vpiStringVal;
            vpi_get_value(suff, &value);
            free(timeformat_info.suff);
            timeformat_info.suff = strdup(value.value.str);

            value.format = vpiIntVal;
            vpi_get_value(wid, &value);
            timeformat_info.width = value.value.integer;
      } else {
            /* If no arguments are given then use the default values. */
            sys_end_of_compile(NULL);
      }

      return 0;
}

static const char *pts_convert(int value)
{
      const char *string;
      switch (value) {
            case   0: string = "1s";    break;
            case  -1: string = "100ms"; break;
            case  -2: string = "10ms";  break;
            case  -3: string = "1ms";   break;
            case  -4: string = "100us"; break;
            case  -5: string = "10us";  break;
            case  -6: string = "1us";   break;
            case  -7: string = "100ns"; break;
            case  -8: string = "10ns";  break;
            case  -9: string = "1ns";   break;
            case -10: string = "100ps"; break;
            case -11: string = "10ps";  break;
            case -12: string = "1ps";   break;
            case -13: string = "100fs"; break;
            case -14: string = "10fs";  break;
            case -15: string = "1fs";   break;
            default: string = "invalid"; assert(0);
      }
      return string;
}

static PLI_INT32 sys_printtimescale_compiletf(PLI_BYTE8*name)
{
      vpiHandle callh   = vpi_handle(vpiSysTfCall, 0);
      vpiHandle argv  = vpi_iterate(vpiArgument, callh);

      if (argv) {
	    vpiHandle arg = vpi_scan(argv);
	    switch (vpi_get(vpiType, arg)) {
		case vpiFunction:
		case vpiIntegerVar:
		case vpiMemory:
		case vpiMemoryWord:
		case vpiModule:
		case vpiNamedBegin:
		case vpiNamedEvent:
		case vpiNamedFork:
		case vpiNet:
		case vpiNetArray:
//		case vpiNetBit: // Unused and unavailable in Icarus
		case vpiParameter:
		case vpiPartSelect:
		case vpiRealVar:
		case vpiReg:
//		case vpiRegBit: // Unused and unavailable in Icarus
		case vpiTask:
		case vpiTimeVar: // Unused in Icarus
		  break;

		default:
		  vpi_printf("ERROR: %s:%d: ", vpi_get_str(vpiFile, callh),
		             (int)vpi_get(vpiLineNo, callh));
		  vpi_printf("%s's argument must have a module, given a %s.\n",
		             name, vpi_get_str(vpiType, arg));
		  vpi_control(vpiFinish, 1);
	    }

	      /* Make sure there are no extra arguments. */
	    check_for_extra_args(argv, callh, name, "one argument", 1);
      }

      return 0;
}

static PLI_INT32 sys_printtimescale_calltf(PLI_BYTE8*xx)
{
      vpiHandle callh   = vpi_handle(vpiSysTfCall, 0);
      vpiHandle argv  = vpi_iterate(vpiArgument, callh);
      vpiHandle item, scope;
      if (!argv) {
            item = sys_func_module(callh);
      } else {
            item = vpi_scan(argv);
            vpi_free_object(argv);
      }

      if (vpi_get(vpiType, item) != vpiModule) {
	    scope = vpi_handle(vpiModule, item);
      } else {
	    scope = item;
      }

      vpi_printf("Time scale of (%s) is ", vpi_get_str(vpiFullName, item));
      vpi_printf("%s / ", pts_convert(vpi_get(vpiTimeUnit, scope)));
      vpi_printf("%s\n", pts_convert(vpi_get(vpiTimePrecision, scope)));

      return 0;
}

static PLI_INT32 sys_end_of_simulation(p_cb_data cb_data)
{
      free(monitor_callbacks);
      monitor_callbacks = 0;
      free(monitor_info.filename);
      free(monitor_info.items);
      monitor_info.items = 0;
      monitor_info.nitems = 0;
      monitor_info.name = 0;

      free(timeformat_info.suff);
      timeformat_info.suff = 0;
      return 0;
}

void sys_display_register()
{
      s_cb_data cb_data;
      s_vpi_systf_data tf_data;

      /*============================== display */
      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$display";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$display";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$info";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$display";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$warning";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$display";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$error";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$display";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$displayh";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$displayh";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$displayo";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$displayo";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$displayb";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$displayb";
      vpi_register_systf(&tf_data);

      /*============================== write */
      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$write";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$write";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$writeh";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$writeh";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$writeo";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$writeo";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$writeb";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$writeb";
      vpi_register_systf(&tf_data);

      /*============================== strobe */
      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$strobe";
      tf_data.calltf    = sys_strobe_calltf;
      tf_data.compiletf = sys_strobe_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$strobe";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$strobeh";
      tf_data.calltf    = sys_strobe_calltf;
      tf_data.compiletf = sys_strobe_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$strobeh";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$strobeo";
      tf_data.calltf    = sys_strobe_calltf;
      tf_data.compiletf = sys_strobe_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$strobeo";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$strobeb";
      tf_data.calltf    = sys_strobe_calltf;
      tf_data.compiletf = sys_strobe_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$strobeb";
      vpi_register_systf(&tf_data);

      /*============================== fstrobe */
      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fstrobe";
      tf_data.calltf    = sys_strobe_calltf;
      tf_data.compiletf = sys_strobe_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fstrobe";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fstrobeh";
      tf_data.calltf    = sys_strobe_calltf;
      tf_data.compiletf = sys_strobe_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fstrobeh";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fstrobeo";
      tf_data.calltf    = sys_strobe_calltf;
      tf_data.compiletf = sys_strobe_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fstrobeo";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fstrobeb";
      tf_data.calltf    = sys_strobe_calltf;
      tf_data.compiletf = sys_strobe_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fstrobeb";
      vpi_register_systf(&tf_data);

      /*============================== monitor */
      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$monitor";
      tf_data.calltf    = sys_monitor_calltf;
      tf_data.compiletf = sys_monitor_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$monitor";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$monitorh";
      tf_data.calltf    = sys_monitor_calltf;
      tf_data.compiletf = sys_monitor_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$monitorh";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$monitoro";
      tf_data.calltf    = sys_monitor_calltf;
      tf_data.compiletf = sys_monitor_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$monitoro";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$monitorb";
      tf_data.calltf    = sys_monitor_calltf;
      tf_data.compiletf = sys_monitor_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$monitorb";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$monitoron";
      tf_data.calltf    = sys_monitoron_calltf;
      tf_data.compiletf = sys_no_arg_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$monitoron";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$monitoroff";
      tf_data.calltf    = sys_monitoroff_calltf;
      tf_data.compiletf = sys_no_arg_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$monitoroff";
      vpi_register_systf(&tf_data);

      /*============================== fdisplay */
      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fdisplay";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fdisplay";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fdisplayh";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fdisplayh";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fdisplayo";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fdisplayo";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fdisplayb";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fdisplayb";
      vpi_register_systf(&tf_data);

      /*============================== fwrite */
      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fwrite";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fwrite";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fwriteh";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fwriteh";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fwriteo";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fwriteo";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$fwriteb";
      tf_data.calltf    = sys_display_calltf;
      tf_data.compiletf = sys_display_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$fwriteb";
      vpi_register_systf(&tf_data);

      /*============================== swrite */
      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$swrite";
      tf_data.calltf    = sys_swrite_calltf;
      tf_data.compiletf = sys_swrite_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$swrite";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$swriteh";
      tf_data.calltf    = sys_swrite_calltf;
      tf_data.compiletf = sys_swrite_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$swriteh";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$swriteo";
      tf_data.calltf    = sys_swrite_calltf;
      tf_data.compiletf = sys_swrite_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$swriteo";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$swriteb";
      tf_data.calltf    = sys_swrite_calltf;
      tf_data.compiletf = sys_swrite_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$swriteb";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$sformat";
      tf_data.calltf    = sys_sformat_calltf;
      tf_data.compiletf = sys_sformat_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$sformat";
      vpi_register_systf(&tf_data);

      /*============================ timeformat */
      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$timeformat";
      tf_data.calltf    = sys_timeformat_calltf;
      tf_data.compiletf = sys_timeformat_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$timeformat";
      vpi_register_systf(&tf_data);

      tf_data.type      = vpiSysTask;
      tf_data.tfname    = "$printtimescale";
      tf_data.calltf    = sys_printtimescale_calltf;
      tf_data.compiletf = sys_printtimescale_compiletf;
      tf_data.sizetf    = 0;
      tf_data.user_data = "$printtimescale";
      vpi_register_systf(&tf_data);

      cb_data.reason = cbEndOfCompile;
      cb_data.time = 0;
      cb_data.cb_rtn = sys_end_of_compile;
      cb_data.user_data = "system";
      vpi_register_cb(&cb_data);

      cb_data.reason = cbEndOfSimulation;
      cb_data.cb_rtn = sys_end_of_simulation;
      cb_data.user_data = "system";
      vpi_register_cb(&cb_data);
}