Skip to content
Snippets Groups Projects
cloc-2.00.pl 726 KiB
Newer Older
#!/usr/bin/env perl
# cloc -- Count Lines of Code                  {{{1
# Copyright (C) 2006-2024 Al Danial <al.danial@gmail.com>
# First release August 2006
#
# Includes code from:
#   - SLOCCount v2.26
#     http://www.dwheeler.com/sloccount/
#     by David Wheeler.
#   - Regexp::Common v2017060201
#     https://metacpan.org/pod/Regexp::Common
#     by Damian Conway and Abigail.
#   - Win32::Autoglob 1.01
#     https://metacpan.org/pod/Win32::Autoglob
#     by Sean M. Burke.
#   - Algorithm::Diff 1.1902
#     https://metacpan.org/pod/Algorithm::Diff
#     by Tye McQueen.
#
# 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 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:
# <http://www.gnu.org/licenses/gpl.txt>.
#
# 1}}}
my $VERSION = "2.00";  # odd number == beta; even number == stable
my $URL     = "github.com/AlDanial/cloc";  # 'https://' pushes header too wide
require 5.10.0;
# use modules                                  {{{1
use warnings;
use strict;

use Getopt::Long;
use File::Basename;
use File::Temp qw { tempfile tempdir };
use File::Find;
use File::Path;
use File::Spec;
use IO::File;
use List::Util qw( min max );
use Cwd;
use POSIX qw { strftime ceil};
# Parallel::ForkManager isn't in the standard distribution.
# Use it only if installed, and only if --processes=N is given.
# The module load happens in get_max_processes().
my $HAVE_Parallel_ForkManager = 0;

# Digest::MD5 isn't in the standard distribution. Use it only if installed.
my $HAVE_Digest_MD5 = 0;
eval "use Digest::MD5;";
if (defined $Digest::MD5::VERSION) {
    $HAVE_Digest_MD5 = 1;
} else {
    warn "Digest::MD5 not installed; will skip file uniqueness checks.\n";
}

# Time::HiRes became standard with Perl 5.8
my $HAVE_Time_HiRes = 0;
eval "use Time::HiRes;";
$HAVE_Time_HiRes = 1 if defined $Time::HiRes::VERSION;

my $HAVE_Rexexp_Common;
# Regexp::Common isn't in the standard distribution.  It will
# be installed in a temp directory if necessary.
eval "use Regexp::Common qw ( comment ) ";
if (defined $Regexp::Common::VERSION) {
    $HAVE_Rexexp_Common = 1;
} else {
    $HAVE_Rexexp_Common = 0;
}

my $HAVE_Algorithm_Diff = 0;
# Algorithm::Diff isn't in the standard distribution.  It will
# be installed in a temp directory if necessary.
eval "use Algorithm::Diff qw ( sdiff ) ";
if (defined $Algorithm::Diff::VERSION) {
    $HAVE_Algorithm_Diff = 1;
} else {
    Install_Algorithm_Diff();
}

# print "2 HAVE_Algorithm_Diff = $HAVE_Algorithm_Diff\n";
# test_alg_diff($ARGV[$#ARGV - 1], $ARGV[$#ARGV]); die;
# die "Hre=$HAVE_Rexexp_Common  Had=$HAVE_Algorithm_Diff";

# Uncomment next two lines when building Windows executable with perl2exe
# or if running on a system that already has Regexp::Common.
#use Regexp::Common;
#$HAVE_Rexexp_Common = 1;

#perl2exe_include "Regexp/Common/whitespace.pm"
#perl2exe_include "Regexp/Common/URI.pm"
#perl2exe_include "Regexp/Common/URI/fax.pm"
#perl2exe_include "Regexp/Common/URI/file.pm"
#perl2exe_include "Regexp/Common/URI/ftp.pm"
#perl2exe_include "Regexp/Common/URI/gopher.pm"
#perl2exe_include "Regexp/Common/URI/http.pm"
#perl2exe_include "Regexp/Common/URI/pop.pm"
#perl2exe_include "Regexp/Common/URI/prospero.pm"
#perl2exe_include "Regexp/Common/URI/news.pm"
#perl2exe_include "Regexp/Common/URI/tel.pm"
#perl2exe_include "Regexp/Common/URI/telnet.pm"
#perl2exe_include "Regexp/Common/URI/tv.pm"
#perl2exe_include "Regexp/Common/URI/wais.pm"
#perl2exe_include "Regexp/Common/CC.pm"
#perl2exe_include "Regexp/Common/SEN.pm"
#perl2exe_include "Regexp/Common/number.pm"
#perl2exe_include "Regexp/Common/delimited.pm"
#perl2exe_include "Regexp/Common/profanity.pm"
#perl2exe_include "Regexp/Common/net.pm"
#perl2exe_include "Regexp/Common/zip.pm"
#perl2exe_include "Regexp/Common/comment.pm"
#perl2exe_include "Regexp/Common/balanced.pm"
#perl2exe_include "Regexp/Common/lingua.pm"
#perl2exe_include "Regexp/Common/list.pm"
#perl2exe_include "File/Glob.pm"

use Text::Tabs qw { expand };
use Cwd qw { cwd };
use File::Glob;
# 1}}}
# Usage information, options processing.       {{{1
my $ON_WINDOWS = 0;
   $ON_WINDOWS = 1 if ($^O =~ /^MSWin/) or ($^O eq "Windows_NT");
if ($ON_WINDOWS and $ENV{'SHELL'}) {
    if ($ENV{'SHELL'} =~ m{^/}) {
        $ON_WINDOWS = 0;  # make Cygwin look like Unix
    } else {
        $ON_WINDOWS = 1;  # MKS defines $SHELL but still acts like Windows
    }
}

my $HAVE_Win32_Long_Path = 0;
# Win32::LongPath is an optional dependency that when available on
# Windows will be used to support reading files past the 255 char
# path length limit.
if ($ON_WINDOWS) {
    eval "use Win32::LongPath;";
    if (defined $Win32::LongPath::VERSION) {
        $HAVE_Win32_Long_Path = 1;
    }
}
my $config_file = '';
if ( $ENV{'HOME'} ) {
    $config_file = File::Spec->catfile( $ENV{'HOME'}, '.config', 'cloc', 'options.txt');
} elsif ( $ENV{'APPDATA'} and $ON_WINDOWS ) {
    $config_file = File::Spec->catfile( $ENV{'APPDATA'}, 'cloc');
}
# $config_file may be updated by check_alternate_config_files()

my $NN     = chr(27) . "[0m";  # normal
   $NN     = "" if $ON_WINDOWS or !(-t STDOUT); # -t STDOUT:  is it a terminal?
my $BB     = chr(27) . "[1m";  # bold
   $BB     = "" if $ON_WINDOWS or !(-t STDOUT);
my $script = basename $0;

#  Intended for v1.88:
#  --git-diff-simindex       Git diff strategy #3:  use git's similarity index
#                            (git diff -M --name-status) to identify file pairs
#                            to compare.  This is especially useful to compare
#                            files that were renamed between the commits.

my $brief_usage  = "
                       cloc -- Count Lines of Code

Usage:
    $script [options] <file(s)/dir(s)/git hash(es)>
        Count physical lines of source code and comments in the given files
        (may be archives such as compressed tarballs or zip files) and/or
        recursively below the given directories or git commit hashes.
        Example:    cloc src/ include/ main.c

    $script [options] --diff <set1>  <set2>
        Compute differences of physical lines of source code and comments
        between any pairwise combination of directory names, archive
        files or git commit hashes.
        Example:    cloc --diff Python-3.5.tar.xz python-3.6/

$script --help  shows full documentation on the options.
https://$URL has numerous examples and more information.
";
my $usage  = "
Usage: $script [options] <file(s)/dir(s)/git hash(es)> | <set 1> <set 2> | <report files>

 Count, or compute differences of, physical lines of source code in the
 given files (may be archives such as compressed tarballs or zip files,
 or git commit hashes or branch names) and/or recursively below the
 given directories.

 ${BB}Input Options${NN}
   --extract-with=<cmd>      This option is only needed if cloc is unable
                             to figure out how to extract the contents of
                             the input file(s) by itself.
                             Use <cmd> to extract binary archive files (e.g.:
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
                             .tar.gz, .zip, .Z).  Use the literal '>FILE<' as
                             a stand-in for the actual file(s) to be
                             extracted.  For example, to count lines of code
                             in the input files
                                gcc-4.2.tar.gz  perl-5.8.8.tar.gz
                             on Unix use
                               --extract-with='gzip -dc >FILE< | tar xf -'
                             or, if you have GNU tar,
                               --extract-with='tar zxf >FILE<'
                             and on Windows use, for example:
                               --extract-with=\"\\\"c:\\Program Files\\WinZip\\WinZip32.exe\\\" -e -o >FILE< .\"
                             (if WinZip is installed there).
   --list-file=<file>        Take the list of file and/or directory names to
                             process from <file>, which has one file/directory
                             name per line.  Only exact matches are counted;
                             relative path names will be resolved starting from
                             the directory where cloc is invoked.  Set <file>
                             to - to read file names from a STDIN pipe.
                             See also --exclude-list-file, --config.
   --diff-list-file=<file>   Take the pairs of file names to be diff'ed from
                             <file>, whose format matches the output of
                             --diff-alignment.  (Run with that option to
                             see a sample.)  The language identifier at the
                             end of each line is ignored.  This enables --diff
                             mode and bypasses file pair alignment logic.
                             Use --diff-list-files to define the file name
                             pairs in separate files. See also --config.
   --diff-list-files <file1> <file2>
                             Compute differences in code and comments between
                             the files and directories listed in <file1> and
                             <file2>.  Each input file should use the same
                             format as --list-file, where there is one file or
                             directory name per line.  Only exact matches are
                             counted; relative path names will be resolved
                             starting from the directory where cloc is invoked.
                             This enables --diff mode.  See also --list-file,
                             --diff-list-file, --diff.
   --vcs=<VCS>               Invoke a system call to <VCS> to obtain a list of
                             files to work on.  If <VCS> is 'git', then will
                             invoke 'git ls-files' to get a file list and
                             'git submodule status' to get a list of submodules
                             whose contents will be ignored.  See also --git
                             which accepts git commit hashes and branch names.
                             If <VCS> is 'svn' then will invoke 'svn list -R'.
                             The primary benefit is that cloc will then skip
                             files explicitly excluded by the versioning tool
                             in question, ie, those in .gitignore or have the
                             svn:ignore property.
                             Alternatively <VCS> may be any system command
                             that generates a list of files.
                             Note:  cloc must be in a directory which can read
                             the files as they are returned by <VCS>.  cloc will
                             not download files from remote repositories.
                             'svn list -R' may refer to a remote repository
                             to obtain file names (and therefore may require
                             authentication to the remote repository), but
                             the files themselves must be local.
                             Setting <VCS> to 'auto' selects between 'git'
                             and 'svn' (or neither) depending on the presence
                             of a .git or .svn subdirectory below the directory
                             where cloc is invoked.
   --unicode                 Check binary files to see if they contain Unicode
                             expanded ASCII text.  This causes performance to
                             drop noticeably.

 ${BB}Processing Options${NN}
   --autoconf                Count .in files (as processed by GNU autoconf) of
                             recognized languages.  See also --no-autogen.
   --by-file                 Report results for every source file encountered.
                             See also --fmt under 'Output Options'.
   --by-file-by-lang         Report results for every source file encountered
                             in addition to reporting by language.
   --config <file>           Read command line switches from <file> instead of
                             the default location of $config_file.
                             The file should contain one switch, along with
                             arguments (if any), per line.  Blank lines and lines
                             beginning with '#' are skipped.  Options given on
                             the command line take priority over entries read from
                             the file.
                             If a directory is also given with any of these
                             switches: --list-file, --exclude-list-file,
                             --read-lang-def, --force-lang-def, --diff-list-file
                             and a config file exists in that directory, it will
                             take priority over $config_file.
   --count-and-diff <set1> <set2>
                             First perform direct code counts of source file(s)
                             of <set1> and <set2> separately, then perform a diff
                             of these.  Inputs may be pairs of files, directories,
                             or archives.  If --out or --report-file is given,
                             three output files will be created, one for each
                             of the two counts and one for the diff.  See also
                             --diff, --diff-alignment, --diff-timeout,
                             --ignore-case, --ignore-whitespace.
   --diff <set1> <set2>      Compute differences in code and comments between
                             source file(s) of <set1> and <set2>.  The inputs
                             may be any mix of files, directories, archives,
                             or git commit hashes.  Use --diff-alignment to
                             generate a list showing which file pairs where
                             compared.  When comparing git branches, only files
                             which have changed in either commit are compared.
                             See also --git, --count-and-diff, --diff-alignment,
                             --diff-list-file, --diff-timeout, --ignore-case,
                             --ignore-whitespace.
   --diff-timeout <N>        Ignore files which take more than <N> seconds
                             to process.  Default is 10 seconds.  Setting <N>
                             to 0 allows unlimited time.  (Large files with many
                             repeated lines can cause Algorithm::Diff::sdiff()
                             to take hours.) See also --timeout.
   --docstring-as-code       cloc considers docstrings to be comments, but this is
                             not always correct as docstrings represent regular
                             strings when they appear on the right hand side of an
                             assignment or as function arguments.  This switch
                             forces docstrings to be counted as code.
   --follow-links            [Unix only] Follow symbolic links to directories
                             (sym links to files are always followed).
                             See also --stat.
   --force-lang=<lang>[,<ext>]
                             Process all files that have a <ext> extension
                             with the counter for language <lang>.  For
                             example, to count all .f files with the
                             Fortran 90 counter (which expects files to
                             end with .f90) instead of the default Fortran 77
                             counter, use
                               --force-lang=\"Fortran 90\",f
                             If <ext> is omitted, every file will be counted
                             with the <lang> counter.  This option can be
                             specified multiple times (but that is only
                             useful when <ext> is given each time).
                             See also --script-lang, --lang-no-ext.
   --force-lang-def=<file>   Load language processing filters from <file>,
                             then use these filters instead of the built-in
                             filters.  Note:  languages which map to the same
                             file extension (for example:
                             MATLAB/Mathematica/Objective-C/MUMPS/Mercury;
                             Pascal/PHP; Lisp/OpenCL; Lisp/Julia; Perl/Prolog)
                             will be ignored as these require additional
                             processing that is not expressed in language
                             definition files.  Use --read-lang-def to define
                             new language filters without replacing built-in
                             filters (see also --write-lang-def,
                             --write-lang-def-incl-dup, --config).
   --git                     Forces the inputs to be interpreted as git targets
                             (commit hashes, branch names, et cetera) if these
                             are not first identified as file or directory
                             names.  This option overrides the --vcs=git logic
                             if this is given; in other words, --git gets its
                             list of files to work on directly from git using
                             the hash or branch name rather than from
                             'git ls-files'.  This option can be used with
                             --diff to perform line count diffs between git
                             commits, or between a git commit and a file,
                             directory, or archive.  Use -v/--verbose to see
                             the git system commands cloc issues.
   --git-diff-rel            Same as --git --diff, or just --diff if the inputs
                             are recognized as git targets.  Only files which
                             have changed in either commit are compared.
   --git-diff-all            Git diff strategy #2:  compare all files in the
                             repository between the two commits.
   --ignore-whitespace       Ignore horizontal white space when comparing files
                             with --diff.  See also --ignore-case.
   --ignore-case             Ignore changes in case within file contents;
                             consider upper- and lowercase letters equivalent
                             when comparing files with --diff.  See also
                             --ignore-whitespace.
   --ignore-case-ext         Ignore case of file name extensions.  This will
                             cause problems counting some languages
                             (specifically, .c and .C are associated with C and
                             C++; this switch would count .C files as C rather
                             than C++ on *nix operating systems).  File name
                             case insensitivity is always true on Windows.
   --lang-no-ext=<lang>      Count files without extensions using the <lang>
                             counter.  This option overrides internal logic
                             for files without extensions (where such files
                             are checked against known scripting languages
                             by examining the first line for #!).  See also
                             --force-lang, --script-lang.
   --max-file-size=<MB>      Skip files larger than <MB> megabytes when
                             traversing directories.  By default, <MB>=100.
                             cloc's memory requirement is roughly twenty times
                             larger than the largest file so running with
                             files larger than 100 MB on a computer with less
                             than 2 GB of memory will cause problems.
                             Note:  this check does not apply to files
                             explicitly passed as command line arguments.
   --no-autogen[=list]       Ignore files generated by code-production systems
                             such as GNU autoconf.  To see a list of these files
                             (then exit), run with --no-autogen list
                             See also --autoconf.
   --no-recurse              Count files in the given directories without
                             recursively descending below them.
   --original-dir            [Only effective in combination with
                             --strip-comments or --strip-code]  Write the stripped
                             files to the same directory as the original files.
   --only-count-files        Only count files by language.  Blank, comment, and
                             code counts will be zero.
   --read-binary-files       Process binary files in addition to text files.
                             This is usually a bad idea and should only be
                             attempted with text files that have embedded
                             binary data.
   --read-lang-def=<file>    Load new language processing filters from <file>
                             and merge them with those already known to cloc.
                             If <file> defines a language cloc already knows
                             about, cloc's definition will take precedence.
                             Use --force-lang-def to over-ride cloc's
                             definitions (see also --write-lang-def,
                             --write-lang-def-incl-dup, --config).
   --script-lang=<lang>,<s>  Process all files that invoke <s> as a #!
                             scripting language with the counter for language
                             <lang>.  For example, files that begin with
                                #!/usr/local/bin/perl5.8.8
                             will be counted with the Perl counter by using
                                --script-lang=Perl,perl5.8.8
                             The language name is case insensitive but the
                             name of the script language executable, <s>,
                             must have the right case.  This option can be
                             specified multiple times.  See also --force-lang,
                             --lang-no-ext.
   --sdir=<dir>              Use <dir> as the scratch directory instead of
                             letting File::Temp chose the location.  Files
                             written to this location are not removed at
                             the end of the run (as they are with File::Temp).
   --skip-leading=<N[,ext]>  Skip the first <N> lines of each file.  If a
                             comma separated list of extensions is also given,
                             only skip lines from those file types.  Example:
                               --skip-leading=10,cpp,h
                             will skip the first ten lines of *.cpp and *.h
                             files.  This is useful for ignoring boilerplate
                             text.
   --skip-uniqueness         Skip the file uniqueness check.  This will give
                             a performance boost at the expense of counting
                             files with identical contents multiple times
                             (if such duplicates exist).
   --stat                    Some file systems (AFS, CD-ROM, FAT, HPFS, SMB)
                             do not have directory 'nlink' counts that match
                             the number of its subdirectories.  Consequently
                             cloc may undercount or completely skip the
                             contents of such file systems.  This switch forces
                             File::Find to stat directories to obtain the
                             correct count.  File search speed will decrease.
                             See also --follow-links.
   --stdin-name=<file>       Give a file name to use to determine the language
                             for standard input.  (Use - as the input name to
                             receive source code via STDIN.)
   --strip-code=<ext>        For each file processed, write to the current
                             directory a version of the file which has blank
                             and code lines, including code with (in-line
                             comments) removed. The name of each stripped file
                             is the original file name with .<ext> appended to
                             it. It is written to the current directory unless
                             --original-dir is on.
   --strip-comments=<ext>    For each file processed, write to the current
                             directory a version of the file which has blank
                             and commented lines removed (in-line comments
                             persist).  The name of each stripped file is the
                             original file name with .<ext> appended to it.
                             It is written to the current directory unless
                             --original-dir is on.
   --strip-str-comments      Replace comment markers embedded in strings with
                             'xx'.  This attempts to work around a limitation
                             in Regexp::Common::Comment where comment markers
                             embedded in strings are seen as actual comment
                             markers and not strings, often resulting in a
                             'Complex regular subexpression recursion limit'
                             warning and incorrect counts.  There are two
                             disadvantages to using this switch:  1/code count
                             performance drops, and 2/code generated with
                             --strip-comments will contain different strings
                             where ever embedded comments are found.
   --sum-reports             Input arguments are report files previously
                             created with the --report-file option in plain
                             format (eg. not JSON, YAML, XML, or SQL).
                             Makes a cumulative set of results containing the
                             sum of data from the individual report files.
   --timeout <N>             Ignore files which take more than <N> seconds
                             to process at any of the language's filter stages.
                             The default maximum number of seconds spent on a
                             filter stage is the number of lines in the file
                             divided by one thousand.  Setting <N> to 0 allows
                             unlimited time.  See also --diff-timeout.
   --processes=NUM           [Available only on systems with a recent version
                             of the Parallel::ForkManager module.  Not
                             available on Windows.] Sets the maximum number of
                             cores that cloc uses.  The default value of 0
                             disables multiprocessing.
   --unix                    Override the operating system autodetection
                             logic and run in UNIX mode.  See also
                             --windows, --show-os.
   --use-sloccount           If SLOCCount is installed, use its compiled
                             executables c_count, java_count, pascal_count,
                             php_count, and xml_count instead of cloc's
                             counters.  SLOCCount's compiled counters are
                             substantially faster than cloc's and may give
                             a performance improvement when counting projects
                             with large files.  However, these cloc-specific
                             features will not be available: --diff,
                             --count-and-diff, --strip-code, --strip-comments,
                             --unicode.
   --windows                 Override the operating system autodetection
                             logic and run in Microsoft Windows mode.
                             See also --unix, --show-os.

 ${BB}Filter Options${NN}
   --include-content=<regex> Only count files containing text that matches the
                             given regular expression.
   --exclude-content=<regex> Exclude files containing text that matches the given
                             regular expression.
   --exclude-dir=<D1>[,D2,]  Exclude the given comma separated directories
                             D1, D2, D3, et cetera, from being scanned.  For
                             example  --exclude-dir=.cache,test  will skip
                             all files and subdirectories that have /.cache/
                             or /test/ as their parent directory.
                             Directories named .bzr, .cvs, .hg, .git, .svn,
                             and .snapshot are always excluded.
                             This option only works with individual directory
                             names so including file path separators is not
                             allowed.  Use --fullpath and --not-match-d=<regex>
                             to supply a regex matching multiple subdirectories.
   --exclude-ext=<ext1>[,<ext2>[...]]
                             Do not count files having the given file name
                             extensions.
   --exclude-lang=<L1>[,L2[...]]
                             Exclude the given comma separated languages
                             L1, L2, L3, et cetera, from being counted.
   --exclude-list-file=<file>  Ignore files and/or directories whose names
                             appear in <file>.  <file> should have one file
                             name per line.  Only exact matches are ignored;
                             relative path names will be resolved starting from
                             the directory where cloc is invoked.
                             See also --list-file, --config.
   --fullpath                Modifies the behavior of --match-f, --not-match-f,
                             and --not-match-d to include the file's path--
                             relative to the directory from which cloc is
                             invoked--in the regex, not just the file's basename.
                             (This does not expand each filename to include its
                             fully qualified absolute path; instead, it uses as
                             much of the path as is passed in to cloc.)
   --include-ext=<ext1>[,ext2[...]]
                             Count only languages having the given comma
                             separated file extensions.  Use --show-ext to
                             see the recognized extensions.
   --include-lang=<L1>[,L2[...]]
                             Count only the given comma separated, case-
                             insensitive languages L1, L2, L3, et cetera.  Use
                             --show-lang to see the list of recognized languages.
   --match-d=<regex>         Only count files in directories matching the Perl
                             regex.  For example
                               --match-d='/(src|include)/'
                             only counts files in directories containing
                             /src/ or /include/.  Unlike --not-match-d,
                             --match-f, and --not-match-f, --match-d always
                             anchors the regex to the directory from which
                             cloc is invoked.
   --not-match-d=<regex>     Count all files except those in directories
                             matching the Perl regex.  Only the trailing
                             directory name is compared, for example, when
                             counting in /usr/local/lib, only 'lib' is
                             compared to the regex.
                             Add --fullpath to compare parent directories, beginning
                             from the directory where cloc is invoked, to the regex.
                             Do not include file path separators at the beginning
                             or end of the regex. This option may be repeated.
   --match-f=<regex>         Only count files whose basenames match the Perl
                             regex.  For example
                               --match-f='^[Ww]idget'
                             only counts files that start with Widget or widget.
                             Add --fullpath to include parent directories
                             in the regex instead of just the basename.
   --not-match-f=<regex>     Count all files except those whose basenames
                             match the Perl regex.  Add --fullpath to include
                             parent directories in the regex instead of just
                             the basename. This option may be repeated.
   --skip-archive=<regex>    Ignore files that end with the given Perl regular
                             expression.  For example, if given
                               --skip-archive='(zip|tar(\.(gz|Z|bz2|xz|7z))?)'
                             the code will skip files that end with .zip,
                             .tar, .tar.gz, .tar.Z, .tar.bz2, .tar.xz, and
                             .tar.7z.
   --skip-win-hidden         On Windows, ignore hidden files.

 ${BB}Debug Options${NN}
   --categorized=<file>      Save file sizes in bytes, identified languages
                             and names of categorized files to <file>.
   --counted=<file>          Save names of processed source files to <file>.
   --diff-alignment=<file>   Write to <file> a list of files and file pairs
                             showing which files were added, removed, and/or
                             compared during a run with --diff.  This switch
                             forces the --diff mode on.
   --explain=<lang>          Print the filters used to remove comments for
                             language <lang> and exit.  In some cases the
                             filters refer to Perl subroutines rather than
                             regular expressions.  An examination of the
                             source code may be needed for further explanation.
   --help                    Print this usage information and exit.
   --found=<file>            Save names of every file found to <file>.
   --ignored=<file>          Save names of ignored files and the reason they
                             were ignored to <file>.
   --print-filter-stages     Print processed source code before and after
                             each filter is applied.
   --show-ext[=<ext>]        Print information about all known (or just the
                             given) file extensions and exit.
   --show-lang[=<lang>]      Print information about all known (or just the
                             given) languages and exit.
   --show-os                 Print the value of the operating system mode
                             and exit.  See also --unix, --windows.
   -v[=<n>]                  Verbose switch (optional numeric value).
   -verbose[=<n>]            Long form of -v.
   --version                 Print the version of this program and exit.
   --write-lang-def=<file>   Writes to <file> the language processing filters
                             then exits.  Useful as a first step to creating
                             custom language definitions. Note: languages which
                             map to the same file extension will be excluded.
                             (See also --force-lang-def, --read-lang-def).
   --write-lang-def-incl-dup=<file>
                             Same as --write-lang-def, but includes duplicated
                             extensions.  This generates a problematic language
                             definition file because cloc will refuse to use
                             it until duplicates are removed.

 ${BB}Output Options${NN}
   --3                       Print third-generation language output.
                             (This option can cause report summation to fail
                             if some reports were produced with this option
                             while others were produced without it.)
   --by-percent  X           Instead of comment and blank line counts, show
                             these values as percentages based on the value
                             of X in the denominator, where X is
                                 c    meaning lines of code
                                 cm   meaning lines of code + comments
                                 cb   meaning lines of code + blanks
                                 cmb  meaning lines of code + comments + blanks
                             For example, if using method 'c' and your code
                             has twice as many lines of comments as lines
                             of code, the value in the comment column will
                             be 200%.  The code column remains a line count.
   --csv                     Write the results as comma separated values.
   --csv-delimiter=<C>       Use the character <C> as the delimiter for comma
                             separated files instead of ,.  This switch forces
   --file-encoding=<E>       Write output files using the <E> encoding instead of
                             the default ASCII (<E> = 'UTF-7').  Examples: 'UTF-16',
                             'euc-kr', 'iso-8859-16'.  Known encodings can be
                             printed with
                               perl -MEncode -e 'print join(\"\\n\", Encode->encodings(\":all\")), \"\\n\"'
   --fmt=<N>                 Alternate text output format where <N> is a number
                             from 1 to 5, or -1 to -5. 'total lines' means the
                             sum of code, comment, and blank lines.  Negative
                             values are the same as the positive values but retain,
                             instead of deleting, the intermediate JSON file that
                             is written.  The JSON file name is randomly generated
                             unless --out/--report-file is given.  The formats are:
                               1:  by language (same as cloc default output)
                               2:  by language with an extra column for total lines
                               3:  by file with language
                               4:  by file with a total lines column
                               5:  by file with language and a total lines column
   --hide-rate               Do not show elapsed time, line processing rate, or
                             file processing rates in the output header. This
                             makes output deterministic.
   --json                    Write the results as JavaScript Object Notation
                             (JSON) formatted output.
   --md                      Write the results as Markdown-formatted text.
   --out=<file>              Synonym for --report-file=<file>.
   --progress-rate=<n>       Show progress update after every <n> files are
                             processed (default <n>=100).  Set <n> to 0 to
                             suppress progress output (useful when redirecting
                             output to STDOUT).
   --quiet                   Suppress all information messages except for
                             the final report.
   --report-file=<file>      Write the results to <file> instead of STDOUT.
   --summary-cutoff=X:N      Aggregate to 'Other' results having X lines
                             below N where X is one of
                                c   meaning lines of code
                                f   meaning files
                                m   meaning lines of comments
                                cm  meaning lines of code + comments
                             Appending a percent sign to N changes
                             the calculation from straight count to
                             percentage.
                             Ignored with --diff or --by-file.
   --sql=<file>              Write results as SQL create and insert statements
                             which can be read by a database program such as
                             SQLite.  If <file> is -, output is sent to STDOUT.
   --sql-append              Append SQL insert statements to the file specified
                             by --sql and do not generate table creation
                             statements.  Only valid with the --sql option.
   --sql-project=<name>      Use <name> as the project identifier for the
                             current run.  Only valid with the --sql option.
   --sql-style=<style>       Write SQL statements in the given style instead
                             of the default SQLite format.  Styles include
                             'Oracle' and 'Named_Columns'.
   --sum-one                 For plain text reports, show the SUM: output line
                             even if only one input file is processed.
   --xml                     Write the results in XML.
   --xsl=<file>              Reference <file> as an XSL stylesheet within
                             the XML output.  If <file> is 1 (numeric one),
                             writes a default stylesheet, cloc.xsl (or
                             cloc-diff.xsl if --diff is also given).
                             This switch forces --xml on.
   --yaml                    Write the results in YAML.

";
#  Help information for options not yet implemented:
#  --inline                  Process comments that appear at the end
#                            of lines containing code.
#  --html                    Create HTML files of each input file showing
#                            comment and code lines in different colors.

$| = 1;  # flush STDOUT
my $start_time = get_time();
my (
    $opt_categorized          ,
    $opt_found                ,
    @opt_force_lang           ,
    $opt_lang_no_ext          ,
    @opt_script_lang          ,
    $opt_count_diff           ,
    $opt_diff                 ,
    $opt_diff_alignment       ,
    $opt_diff_list_file       ,
    $opt_diff_list_files      ,
    $opt_diff_timeout         ,
    $opt_timeout              ,
    $opt_html                 ,
    $opt_ignored              ,
    $opt_counted              ,
    $opt_show_ext             ,
    $opt_show_lang            ,
    $opt_progress_rate        ,
    $opt_print_filter_stages  ,
    $opt_v                    ,
    $opt_vcs                  ,
    $opt_version              ,
    $opt_include_content      ,
    $opt_exclude_content      ,
    $opt_exclude_lang         ,
    $opt_exclude_list_file    ,
    $opt_exclude_dir          ,
    $opt_explain              ,
    $opt_include_ext          ,
    $opt_include_lang         ,
    $opt_force_lang_def       ,
    $opt_read_lang_def        ,
    $opt_write_lang_def       ,
    $opt_write_lang_def_incl_dup,
    $opt_strip_code           ,
    $opt_strip_comments       ,
    $opt_original_dir         ,
    $opt_quiet                ,
    $opt_report_file          ,
    $opt_sdir                 ,
    $opt_sum_reports          ,
    $opt_hide_rate            ,
    $opt_processes            ,
    $opt_unicode              ,
    $opt_no3                  ,   # accept it but don't use it
    $opt_3                    ,
    $opt_extract_with         ,
    $opt_by_file              ,
    $opt_by_file_by_lang      ,
    $opt_by_percent           ,
    $opt_xml                  ,
    $opt_xsl                  ,
    $opt_yaml                 ,
    $opt_csv                  ,
    $opt_csv_delimiter        ,
    $opt_fullpath             ,
    $opt_json                 ,
    $opt_md                   ,
    $opt_match_f              ,
    @opt_not_match_f          ,
    $opt_match_d              ,
    @opt_not_match_d          ,
    $opt_skip_uniqueness      ,
    $opt_list_file            ,
    $opt_help                 ,
    $opt_skip_win_hidden      ,
    $opt_read_binary_files    ,
    $opt_sql                  ,
    $opt_sql_append           ,
    $opt_sql_project          ,
    $opt_sql_style            ,
    $opt_inline               ,
    $opt_exclude_ext          ,
    $opt_ignore_whitespace    ,
    $opt_ignore_case          ,
    $opt_ignore_case_ext      ,
    $opt_follow_links         ,
    $opt_autoconf             ,
    $opt_sum_one              ,
    $opt_stdin_name           ,
    $opt_force_on_windows     ,
    $opt_force_on_unix        ,   # actually forces !$ON_WINDOWS
    $opt_show_os              ,
    $opt_skip_archive         ,
    $opt_max_file_size        ,   # in MB
    $opt_use_sloccount        ,
    $opt_no_autogen           ,
    $opt_force_git            ,
    $opt_git_diff_rel         ,
    $opt_git_diff_all         ,
    $opt_git_diff_simindex    ,
    $opt_config_file          ,
    $opt_strip_str_comments   ,
    $opt_file_encoding        ,
    $opt_docstring_as_code    ,
    $opt_stat                 ,
    $opt_summary_cutoff       ,
    $opt_skip_leading         ,
    $opt_no_recurse           ,
    $opt_only_count_files     ,
    $opt_fmt                  ,
   );

my $getopt_success = GetOptions(             # {{{1
   "by_file|by-file"                         => \$opt_by_file             ,
   "by_file_by_lang|by-file-by-lang"         => \$opt_by_file_by_lang     ,
   "categorized=s"                           => \$opt_categorized         ,
   "counted=s"                               => \$opt_counted             ,
   "include_ext|include-ext=s"               => \$opt_include_ext         ,
   "include_lang|include-lang=s"             => \$opt_include_lang        ,
   "include_content|include-content=s"       => \$opt_include_content     ,
   "exclude_content|exclude-content=s"       => \$opt_exclude_content     ,
   "exclude_lang|exclude-lang=s"             => \$opt_exclude_lang        ,
   "exclude_dir|exclude-dir=s"               => \$opt_exclude_dir         ,
   "exclude_list_file|exclude-list-file=s"   => \$opt_exclude_list_file   ,
   "explain=s"                               => \$opt_explain             ,
   "extract_with|extract-with=s"             => \$opt_extract_with        ,
   "found=s"                                 => \$opt_found               ,
   "count_and_diff|count-and-diff"           => \$opt_count_diff          ,
   "diff"                                    => \$opt_diff                ,
   "diff-alignment|diff_alignment=s"         => \$opt_diff_alignment      ,
   "diff-timeout|diff_timeout=i"             => \$opt_diff_timeout        ,
   "diff-list-file|diff_list_file=s"         => \$opt_diff_list_file      ,
   "diff-list-files|diff_list_files"         => \$opt_diff_list_files     ,
   "timeout=i"                               => \$opt_timeout             ,
   "html"                                    => \$opt_html                ,
   "ignored=s"                               => \$opt_ignored             ,
   "quiet"                                   => \$opt_quiet               ,
   "force_lang_def|force-lang-def=s"         => \$opt_force_lang_def      ,
   "read_lang_def|read-lang-def=s"           => \$opt_read_lang_def       ,
   "show_ext|show-ext:s"                     => \$opt_show_ext            ,
   "show_lang|show-lang:s"                   => \$opt_show_lang           ,
   "progress_rate|progress-rate=i"           => \$opt_progress_rate       ,
   "print_filter_stages|print-filter-stages" => \$opt_print_filter_stages ,
   "report_file|report-file=s"               => \$opt_report_file         ,
   "out=s"                                   => \$opt_report_file         ,
   "script_lang|script-lang=s"               => \@opt_script_lang         ,
   "sdir=s"                                  => \$opt_sdir                ,
   "skip_uniqueness|skip-uniqueness"         => \$opt_skip_uniqueness     ,
   "strip_code|strip-code=s"                 => \$opt_strip_code          ,
   "strip_comments|strip-comments=s"         => \$opt_strip_comments      ,
   "original_dir|original-dir"               => \$opt_original_dir        ,
   "sum_reports|sum-reports"                 => \$opt_sum_reports         ,
   "hide_rate|hide-rate"                     => \$opt_hide_rate           ,
   "processes=n"                             => \$opt_processes           ,
   "unicode"                                 => \$opt_unicode             ,
   "no3"                                     => \$opt_no3                 ,  # ignored
   "3"                                       => \$opt_3                   ,
   "v|verbose:i"                             => \$opt_v                   ,
   "vcs=s"                                   => \$opt_vcs                 ,
   "version"                                 => \$opt_version             ,
   "write_lang_def|write-lang-def=s"         => \$opt_write_lang_def      ,
   "write_lang_def_incl_dup|write-lang-def-incl-dup=s" => \$opt_write_lang_def_incl_dup,
   "xml"                                     => \$opt_xml                 ,
   "xsl=s"                                   => \$opt_xsl                 ,
   "force_lang|force-lang=s"                 => \@opt_force_lang          ,
   "lang_no_ext|lang-no-ext=s"               => \$opt_lang_no_ext         ,
   "yaml"                                    => \$opt_yaml                ,
   "csv"                                     => \$opt_csv                 ,
   "csv_delimiter|csv-delimiter=s"           => \$opt_csv_delimiter       ,
   "json"                                    => \$opt_json                ,
   "md"                                      => \$opt_md                  ,
   "fullpath"                                => \$opt_fullpath            ,
   "match_f|match-f=s"                       => \$opt_match_f             ,
   "not_match_f|not-match-f=s"               => \@opt_not_match_f         ,
   "match_d|match-d=s"                       => \$opt_match_d             ,
   "not_match_d|not-match-d=s"               => \@opt_not_match_d         ,
   "list_file|list-file=s"                   => \$opt_list_file           ,
   "help"                                    => \$opt_help                ,
   "skip_win_hidden|skip-win-hidden"         => \$opt_skip_win_hidden     ,
   "read_binary_files|read-binary-files"     => \$opt_read_binary_files   ,
   "sql=s"                                   => \$opt_sql                 ,
   "sql_project|sql-project=s"               => \$opt_sql_project         ,
   "sql_append|sql-append"                   => \$opt_sql_append          ,
   "sql_style|sql-style=s"                   => \$opt_sql_style           ,
   "inline"                                  => \$opt_inline              ,
   "exclude_ext|exclude-ext=s"               => \$opt_exclude_ext         ,
   "ignore_whitespace|ignore-whitespace"     => \$opt_ignore_whitespace   ,
   "ignore_case|ignore-case"                 => \$opt_ignore_case         ,
   "ignore_case_ext|ignore-case-ext"         => \$opt_ignore_case_ext     ,
   "follow_links|follow-links"               => \$opt_follow_links        ,
   "autoconf"                                => \$opt_autoconf            ,
   "sum_one|sum-one"                         => \$opt_sum_one             ,
   "by_percent|by-percent=s"                 => \$opt_by_percent          ,
   "stdin_name|stdin-name=s"                 => \$opt_stdin_name          ,
   "windows"                                 => \$opt_force_on_windows    ,
   "unix"                                    => \$opt_force_on_unix       ,
   "show_os|show-os"                         => \$opt_show_os             ,
   "skip_archive|skip-archive=s"             => \$opt_skip_archive        ,
   "max_file_size|max-file-size=f"           => \$opt_max_file_size       ,
   "use_sloccount|use-sloccount"             => \$opt_use_sloccount       ,
   "no_autogen|no-autogen"                   => \$opt_no_autogen          ,
   "git"                                     => \$opt_force_git           ,
   "git_diff_rel|git-diff-rel"               => \$opt_git_diff_rel        ,
   "git_diff_all|git-diff-all"               => \$opt_git_diff_all        ,
#  "git_diff_simindex|git-diff-simindex"     => \$opt_git_diff_simindex   ,
   "config=s"                                => \$opt_config_file         ,
   "strip_str_comments|strip-str-comments"   => \$opt_strip_str_comments  ,
   "file_encoding|file-encoding=s"           => \$opt_file_encoding       ,
   "docstring_as_code|docstring-as-code"     => \$opt_docstring_as_code   ,
   "stat"                                    => \$opt_stat                ,
   "summary_cutoff|summary-cutoff=s"         => \$opt_summary_cutoff      ,
   "skip_leading|skip-leading:s"             => \$opt_skip_leading        ,
   "no_recurse|no-recurse"                   => \$opt_no_recurse          ,
   "only_count_files|only-count-files"       => \$opt_only_count_files    ,
   "fmt=i"                                   => \$opt_fmt                 ,
  );
# 1}}}
$config_file = $opt_config_file if defined $opt_config_file;
load_from_config_file($config_file,          # {{{2
                                                \$opt_by_file             ,
                                                \$opt_by_file_by_lang     ,
                                                \$opt_categorized         ,
                                                \$opt_counted             ,
                                                \$opt_include_ext         ,
                                                \$opt_include_lang        ,
                                                \$opt_include_content     ,
                                                \$opt_exclude_content     ,
                                                \$opt_exclude_lang        ,
                                                \$opt_exclude_dir         ,
                                                \$opt_exclude_list_file   ,
                                                \$opt_explain             ,
                                                \$opt_extract_with        ,
                                                \$opt_found               ,
                                                \$opt_count_diff          ,
                                                \$opt_diff_list_files     ,
                                                \$opt_diff                ,
                                                \$opt_diff_alignment      ,
                                                \$opt_diff_timeout        ,
                                                \$opt_timeout             ,
                                                \$opt_html                ,
                                                \$opt_ignored             ,
                                                \$opt_quiet               ,
                                                \$opt_force_lang_def      ,
                                                \$opt_read_lang_def       ,
                                                \$opt_show_ext            ,
                                                \$opt_show_lang           ,
                                                \$opt_progress_rate       ,
                                                \$opt_print_filter_stages ,
                                                \$opt_report_file         ,
                                                \@opt_script_lang         ,
                                                \$opt_sdir                ,
                                                \$opt_skip_uniqueness     ,
                                                \$opt_strip_code          ,
                                                \$opt_strip_comments      ,
                                                \$opt_original_dir        ,
                                                \$opt_sum_reports         ,
                                                \$opt_hide_rate           ,
                                                \$opt_processes           ,
                                                \$opt_unicode             ,
                                                \$opt_3                   ,
                                                \$opt_v                   ,
                                                \$opt_vcs                 ,
                                                \$opt_version             ,
                                                \$opt_write_lang_def      ,
                                                \$opt_write_lang_def_incl_dup,
                                                \$opt_xml                 ,
                                                \$opt_xsl                 ,
                                                \@opt_force_lang          ,
                                                \$opt_lang_no_ext         ,
                                                \$opt_yaml                ,
                                                \$opt_csv                 ,
                                                \$opt_csv_delimiter       ,
                                                \$opt_json                ,
                                                \$opt_md                  ,
                                                \$opt_fullpath            ,
                                                \$opt_match_f             ,
                                                \@opt_not_match_f         ,
                                                \$opt_match_d             ,
                                                \@opt_not_match_d         ,
                                                \$opt_list_file           ,
                                                \$opt_help                ,
                                                \$opt_skip_win_hidden     ,
                                                \$opt_read_binary_files   ,
                                                \$opt_sql                 ,
                                                \$opt_sql_project         ,
                                                \$opt_sql_append          ,
                                                \$opt_sql_style           ,
                                                \$opt_inline              ,
                                                \$opt_exclude_ext         ,
                                                \$opt_ignore_whitespace   ,
                                                \$opt_ignore_case         ,
                                                \$opt_ignore_case_ext     ,
                                                \$opt_follow_links        ,
                                                \$opt_autoconf            ,
                                                \$opt_sum_one             ,
                                                \$opt_by_percent          ,
                                                \$opt_stdin_name          ,
                                                \$opt_force_on_windows    ,
                                                \$opt_force_on_unix       ,
                                                \$opt_show_os             ,
                                                \$opt_skip_archive        ,
                                                \$opt_max_file_size       ,
                                                \$opt_use_sloccount       ,
                                                \$opt_no_autogen          ,
                                                \$opt_force_git           ,
                                                \$opt_strip_str_comments  ,
                                                \$opt_file_encoding       ,
                                                \$opt_docstring_as_code   ,
                                                \$opt_stat                ,
);  # 2}}} Not pretty.  Not at all.
if ($opt_version) {
    printf "$VERSION\n";
    exit;
}
my $opt_git = 0;
$opt_git = 1 if defined($opt_git_diff_all) or
                defined($opt_git_diff_rel) or
                (defined($opt_vcs) and ($opt_vcs eq "git"));
$opt_by_file  = 1 if defined  $opt_by_file_by_lang;
$opt_fmt = 0 unless defined $opt_fmt;
if ($opt_fmt) {
    $opt_by_file = 1;
    $opt_json = 1;
    if (!defined $opt_report_file) {
    my $fh;
    ($fh, $opt_report_file) = tempfile(UNLINK => 0, DIR => ".", SUFFIX => ".json" );
    $fh->close; # will be opened later by the JSON writer
    }
}
my $CLOC_XSL = "cloc.xsl"; # created with --xsl
   $CLOC_XSL = "cloc-diff.xsl" if $opt_diff;
die "\n" unless $getopt_success;
print $usage and exit if $opt_help;
my %Exclude_Language = ();
   %Exclude_Language = map { $_ => 1 } split(/,/, $opt_exclude_lang)
        if $opt_exclude_lang;
my %Exclude_Dir      = ();
   %Exclude_Dir      = map { $_ => 1 } split(/,/, $opt_exclude_dir )
        if $opt_exclude_dir ;
die unless exclude_dir_validates(\%Exclude_Dir);
my %Include_Ext = ();
   %Include_Ext = map { $_ => 1 } split(/,/, $opt_include_ext)
        if $opt_include_ext;
my %Include_Language = (); # keys are lower case language names
   %Include_Language = map { lc($_) => 1 } split(/,/, $opt_include_lang)
        if $opt_include_lang;
# Forcibly exclude .svn, .cvs, .hg, .git, .bzr directories.  The contents of these
# directories often conflict with files of interest.
$opt_exclude_dir       = 1;
$Exclude_Dir{".svn"}   = 1;
$Exclude_Dir{".cvs"}   = 1;
$Exclude_Dir{".hg"}    = 1;
$Exclude_Dir{".git"}   = 1;
$Exclude_Dir{".bzr"}   = 1;
$Exclude_Dir{".snapshot"} = 1;  # NetApp backups
$Exclude_Dir{".config"} = 1;
$opt_count_diff        = defined $opt_count_diff ? 1 : 0;
$opt_diff              = 1  if $opt_diff_alignment    or
                               $opt_diff_list_file    or
                               $opt_diff_list_files   or
                               $opt_git_diff_rel      or
                               $opt_git_diff_all      or
                               $opt_git_diff_simindex;
$opt_force_git         = 1  if $opt_git_diff_rel      or
                               $opt_git_diff_all      or
                               $opt_git_diff_simindex;
$opt_diff_alignment    = 0  if $opt_diff_list_file;
$opt_exclude_ext       = "" unless $opt_exclude_ext;
$opt_ignore_whitespace = 0  unless $opt_ignore_whitespace;
$opt_ignore_case       = 0  unless $opt_ignore_case;
$opt_ignore_case_ext   = 0  unless $opt_ignore_case_ext;
$opt_lang_no_ext       = 0  unless $opt_lang_no_ext;
$opt_follow_links      = 0  unless $opt_follow_links;
if (defined $opt_diff_timeout) {
    # if defined but with a value of <= 0, set to 2^31-1 seconds = 68 years
    $opt_diff_timeout = 2**31-1 unless $opt_diff_timeout > 0;
} else {
    $opt_diff_timeout  =10; # seconds
}
if (defined $opt_timeout) {
    # if defined but with a value of <= 0, set to 2^31-1 seconds = 68 years
    $opt_timeout = 2**31-1 unless $opt_timeout > 0;
    # else is computed dynamically, ref $max_duration_sec
}
$opt_csv               = 0  unless defined $opt_csv;
$opt_csv               = 1  if $opt_csv_delimiter;
$ON_WINDOWS            = 1  if $opt_force_on_windows;
$ON_WINDOWS            = 0  if $opt_force_on_unix;
$opt_max_file_size     = 100 unless $opt_max_file_size;
my $HAVE_SLOCCOUNT_c_count = 0;
if (!$ON_WINDOWS and $opt_use_sloccount) {
    # Only bother doing this kludgey test is user explicitly wants
    # to use SLOCCount.  Debian based systems will hang if just doing
    #  external_utility_exists("c_count")
    # if c_count is in $PATH; c_count expects to have input.
    $HAVE_SLOCCOUNT_c_count = external_utility_exists("c_count /bin/sh");
}
if ($opt_use_sloccount) {
    if (!$HAVE_SLOCCOUNT_c_count) {
        warn "c_count could not be found; ignoring --use-sloccount\n";
        $opt_use_sloccount = 0;
    } else {
        warn "Using c_count, php_count, xml_count, pascal_count from SLOCCount\n";
        warn "--diff is disabled with --use-sloccount\n" if $opt_diff;
        warn "--count-and-diff is disabled with --use-sloccount\n" if $opt_count_diff;
        warn "--unicode is disabled with --use-sloccount\n" if $opt_unicode;
        warn "--strip-comments is disabled with --use-sloccount\n" if $opt_strip_comments;
        warn "--strip-code is disabled with --use-sloccount\n" if $opt_strip_code;
        $opt_diff           = 0;
        $opt_count_diff     = undef;
        $opt_unicode        = 0;
        $opt_strip_comments = 0;
        $opt_strip_code     = 0;
    }
}
die "--strip-comments and --strip-code are mutually exclusive\n" if
    $opt_strip_comments and $opt_strip_code;
$opt_vcs = 0 if $opt_force_git;

# replace Windows path separators with /
if ($ON_WINDOWS) {
    map { s{\\}{/}g } @ARGV;
    if ($opt_git) {
        # PowerShell tab expansion automatically prefixes local directories
        # with ".\" (now mapped to "./").   git ls-files output does not
        # include this.  Strip this prefix to permit clean matches.
        map { s{^\./}{} } @ARGV;
    }
}

my @COUNT_DIFF_ARGV        = undef;
my $COUNT_DIFF_report_file = undef;
if ($opt_count_diff and !$opt_diff_list_file) {
    die "--count-and-diff requires two arguments; got ", scalar @ARGV, "\n"
        if scalar @ARGV != 2;
    # prefix with a dummy term so that $opt_count_diff is the
    # index into @COUNT_DIFF_ARGV to work on at each pass
    @COUNT_DIFF_ARGV = (undef, $ARGV[0],
                               $ARGV[1],
                              [$ARGV[0], $ARGV[1]]);  # 3rd pass: diff them
    $COUNT_DIFF_report_file = $opt_report_file if $opt_report_file;
}

# Options defaults:
$opt_quiet         =   1 if ($opt_md or $opt_json or !(-t STDOUT))
                            and !defined $opt_report_file;
$opt_progress_rate = 100 unless defined $opt_progress_rate;
$opt_progress_rate =   0 if     defined $opt_quiet;
if (!defined $opt_v) {
    $opt_v  = 0;
} elsif (!$opt_v) {
    $opt_v  = 1;
}
if (defined $opt_xsl) {
    $opt_xsl = $CLOC_XSL if $opt_xsl eq "1";
    $opt_xml = 1;
}
my $skip_generate_report = 0;
$opt_sql_style = 0 unless defined $opt_sql_style;
$opt_sql = 0 unless $opt_sql_style or defined $opt_sql;
if ($opt_sql eq "-" || $opt_sql eq "1") { # stream SQL output to STDOUT
    $opt_quiet            = 1;
    $skip_generate_report = 1;
    $opt_by_file          = 1;
    $opt_sum_reports      = 0;
    $opt_progress_rate    = 0;
} elsif ($opt_sql)  { # write SQL output to a file
    $opt_by_file          = 1;
    $skip_generate_report = 1;
    $opt_sum_reports      = 0;
}
if ($opt_sql_style) {
    $opt_sql_style = lc $opt_sql_style;
    if (!grep { lc $_ eq $opt_sql_style } qw ( Oracle Named_Columns )) {
        die "'$opt_sql_style' is not a recognized SQL style.\n";
    }
}
$opt_by_percent = '' unless defined $opt_by_percent;
if ($opt_by_percent and $opt_by_percent !~ m/^(c|cm|cb|cmb)$/i) {
    die "--by-percent must be either 'c', 'cm', 'cb', or 'cmb'\n";
}
$opt_by_percent = lc $opt_by_percent;

if (defined $opt_vcs) {
    if ($opt_vcs eq "auto") {
        if      (is_dir(".git")) {
            $opt_vcs = "git";
        } elsif (is_dir(".svn")) {
            $opt_vcs = "svn";
        } else {
            warn "--vcs auto:  unable to determine versioning system\n";
        }
    }
    if      ($opt_vcs eq "git") {
        $opt_vcs = "git ls-files";
        my @submodules = invoke_generator('git submodule status', \@ARGV);
        foreach my $SM (@submodules) {
            $SM =~ s/^\s+//;        # may have leading space
            $SM =~ s/\(\S+\)\s*$//; # may end with something like (heads/master)
            my ($checksum, $dir) = split(' ', $SM, 2);
            $dir =~ s/\s+$//;
            $Exclude_Dir{$dir} = 1;
        }
    } elsif ($opt_vcs eq "svn") {
        $opt_vcs = "svn list -R";
    }
}

my $list_no_autogen = 0;
if (defined $opt_no_autogen and scalar @ARGV == 1 and $ARGV[0] eq "list") {
    $list_no_autogen = 1;
}
if ($opt_summary_cutoff) {
    my $error = summary_cutoff_error($opt_summary_cutoff);
    die "$error\n" if $error;
}

if (!$opt_config_file) {
    # if not explicitly given, look for a config file in other
    # possible locations
    my $other_loc = check_alternate_config_files($opt_list_file,
        $opt_exclude_list_file, $opt_read_lang_def, $opt_force_lang_def,
        $opt_diff_list_file);
    $opt_config_file = $other_loc if $other_loc;
}

die $brief_usage unless defined $opt_version         or
                        defined $opt_show_lang       or
                        defined $opt_show_ext        or
                        defined $opt_show_os         or
                        defined $opt_write_lang_def  or
                        defined $opt_write_lang_def_incl_dup  or
                        defined $opt_list_file       or
                        defined $opt_diff_list_file  or
                        defined $opt_vcs             or
                        defined $opt_xsl             or
                        defined $opt_explain         or
                        $list_no_autogen             or
                        scalar @ARGV >= 1;
if (!$opt_diff_list_file) {
    die "--diff requires two arguments; got ", scalar @ARGV, "\n"
        if $opt_diff and !$opt_sum_reports and scalar @ARGV != 2;
    die "--diff arguments are identical; nothing done", "\n"
        if $opt_diff and !$opt_sum_reports and scalar @ARGV == 2
                                           and $ARGV[0] eq $ARGV[1];
}
trick_pp_packer_encode() if $ON_WINDOWS and $opt_file_encoding;
$File::Find::dont_use_nlink = 1 if $opt_stat or top_level_SMB_dir(\@ARGV);
my @git_similarity = (); # only populated with --git-diff-simindex
my %git_metadata   = ();
get_git_metadata(\@ARGV, \%git_metadata) if $opt_force_git;
#use Data::Dumper;
#print Dumper(\%git_metadata);
replace_git_hash_with_tarfile(\@ARGV, \@git_similarity);
# 1}}}
# Step 1:  Initialize global constants.        {{{1
#
my $nFiles_Found = 0;  # updated in make_file_list
my (%Language_by_Extension, %Language_by_Script,
    %Filters_by_Language, %Not_Code_Extension, %Not_Code_Filename,
    %Language_by_File, %Scale_Factor, %Known_Binary_Archives,
    %Language_by_Prefix, %EOL_Continuation_re,
   );
my $ALREADY_SHOWED_HEADER = 0;
my $ALREADY_SHOWED_XML_SECTION = 0;
my %Error_Codes = ( 'Unable to read'                => -1,
                    'Neither file nor directory'    => -2,
                    'Diff error (quoted comments?)' => -3,
                    'Diff error, exceeded timeout'  => -4,
                    'Line count, exceeded timeout'  => -5,
                  );
my %Extension_Collision = (
    'ADSO/IDSM'                                     => [ 'adso' ] ,
    'C#/Smalltalk'                                  => [ 'cs'   ] ,
    'D/dtrace'                                      => [ 'd'    ] ,
    'F#/Forth'                                      => [ 'fs'   ] ,
    'Fortran 77/Forth'                              => [ 'f', 'for' ] ,
    'IDL/Qt Project/Prolog/ProGuard'                => [ 'pro'  ] ,
    'Lisp/Julia'                                    => [ 'jl'   ] ,
    'Lisp/OpenCL'                                   => [ 'cl'   ] ,
    'MATLAB/Mathematica/Objective-C/MUMPS/Mercury'  => [ 'm'    ] ,
    'Pascal/Puppet'                                 => [ 'pp'   ] ,
    'Perl/Prolog'                                   => [ 'pl', 'PL'  ] ,
    'PHP/Pascal/Fortran'                            => [ 'inc'  ] ,
    'Raku/Prolog'                                   => [ 'p6', 'P6'  ] ,
    'Qt/Glade'                                      => [ 'ui'   ] ,
    'TypeScript/Qt Linguist'                        => [ 'ts'   ] ,
    'Verilog-SystemVerilog/Coq'                     => [ 'v'    ] ,
    'Visual Basic/TeX/Apex Class'                   => [ 'cls'  ] ,
    'Scheme/SaltStack'                              => [ 'sls'  ] ,
);
my @Autogen_to_ignore = no_autogen_files($list_no_autogen);
if ($opt_force_lang_def) {
    # replace cloc's definitions
    read_lang_def(
        $opt_force_lang_def    , #        Sample values:
        \%Language_by_Extension, # Language_by_Extension{f}    = 'Fortran 77'
        \%Language_by_Script   , # Language_by_Script{sh}      = 'Bourne Shell'
        \%Language_by_File     , # Language_by_File{makefile}  = 'make'
        \%Filters_by_Language  , # Filters_by_Language{Bourne Shell}[0] =
                                 #      [ 'remove_matches' , '^\s*#'  ]
        \%Not_Code_Extension   , # Not_Code_Extension{jpg}     = 1
        \%Not_Code_Filename    , # Not_Code_Filename{README}   = 1
        \%Scale_Factor         , # Scale_Factor{Perl}          = 4.0
        \%EOL_Continuation_re  , # EOL_Continuation_re{C++}    = '\\$'
        );
} else {
    set_constants(               #
        \%Language_by_Extension, # Language_by_Extension{f}    = 'Fortran 77'
        \%Language_by_Script   , # Language_by_Script{sh}      = 'Bourne Shell'
        \%Language_by_File     , # Language_by_File{makefile}  = 'make'
        \%Language_by_Prefix   , # Language_by_Prefix{Dockerfile}  = 'Dockerfile'
        \%Filters_by_Language  , # Filters_by_Language{Bourne Shell}[0] =
                                 #      [ 'remove_matches' , '^\s*#'  ]
        \%Not_Code_Extension   , # Not_Code_Extension{jpg}     = 1
        \%Not_Code_Filename    , # Not_Code_Filename{README}   = 1
        \%Scale_Factor         , # Scale_Factor{Perl}          = 4.0
        \%Known_Binary_Archives, # Known_Binary_Archives{.tar} = 1
        \%EOL_Continuation_re  , # EOL_Continuation_re{C++}    = '\\$'
        );
        if ($opt_no_autogen) {
            foreach my $F (@Autogen_to_ignore) { $Not_Code_Filename{ $F } = 1; }
        }
}
if ($opt_read_lang_def) {
    # augment cloc's definitions (keep cloc's where there are overlaps)
    merge_lang_def(
        $opt_read_lang_def     , #        Sample values:
        \%Language_by_Extension, # Language_by_Extension{f}    = 'Fortran 77'
        \%Language_by_Script   , # Language_by_Script{sh}      = 'Bourne Shell'
        \%Language_by_File     , # Language_by_File{makefile}  = 'make'
        \%Filters_by_Language  , # Filters_by_Language{Bourne Shell}[0] =
                                 #      [ 'remove_matches' , '^\s*#'  ]
        \%Not_Code_Extension   , # Not_Code_Extension{jpg}     = 1
        \%Not_Code_Filename    , # Not_Code_Filename{README}   = 1
        \%Scale_Factor         , # Scale_Factor{Perl}          = 4.0
        \%EOL_Continuation_re  , # EOL_Continuation_re{C++}    = '\\$'
        );
}
if ($opt_lang_no_ext and !defined $Filters_by_Language{$opt_lang_no_ext}) {
    die_unknown_lang($opt_lang_no_ext, "--lang-no-ext")
}
check_scale_existence(\%Filters_by_Language, \%Language_by_Extension,
                      \%Scale_Factor);

my $nCounted = 0;

# Process command line provided extension-to-language mapping overrides.
# Make a hash of known languages in lower case for easier matching.
my %Recognized_Language_lc = (); # key = language name in lc, value = true name
foreach my $language (keys %Filters_by_Language) {
    my $lang_lc = lc $language;
    $Recognized_Language_lc{$lang_lc} = $language;
}
my %Forced_Extension = (); # file name extensions which user wants to count
my $All_One_Language = 0;  # set to !0 if --force-lang's <ext> is missing
foreach my $pair (@opt_force_lang) {
    my ($lang, $extension) = split(',', $pair);
    my $lang_lc = lc $lang;
    if (defined $extension) {
        $Forced_Extension{$extension} = $lang;

        die_unknown_lang($lang, "--force-lang")
            unless $Recognized_Language_lc{$lang_lc};

        $Language_by_Extension{$extension} = $Recognized_Language_lc{$lang_lc};
    } else {
        # the scary case--count everything as this language
        $All_One_Language = $Recognized_Language_lc{$lang_lc};
    }
}

foreach my $pair (@opt_script_lang) {
    my ($lang, $script_name) = split(',', $pair);
    my $lang_lc = lc $lang;
    if (!defined $script_name) {
        die "The --script-lang option requires a comma separated pair of ".
            "strings.\n";
    }

    die_unknown_lang($lang, "--script-lang")
        unless $Recognized_Language_lc{$lang_lc};

    $Language_by_Script{$script_name} = $Recognized_Language_lc{$lang_lc};
}

# If user provided a language definition file, make sure those
# extensions aren't rejected.
foreach my $ext (%Language_by_Extension) {
    next unless defined $Not_Code_Extension{$ext};
    delete $Not_Code_Extension{$ext};
}

# If user provided file extensions to ignore, add these to
# the exclusion list.
foreach my $ext (map { $_ => 1 } split(/,/, $opt_exclude_ext ) ) {
    $ext = lc $ext if $ON_WINDOWS or $opt_ignore_case_ext;
    $Not_Code_Extension{$ext} = 1;
}

# If SQL or --by-file output is requested, keep track of directory names
# generated by File::Temp::tempdir and used to temporarily hold the results
# of compressed archives.  Contents of the SQL table 't' will be much
# cleaner if these meaningless directory names are stripped from the front
# of files pulled from the archives.
my %TEMP_DIR = ();
my $TEMP_OFF =  0;  # Needed for --sdir; keep track of the number of
                    # scratch directories made in this run to avoid
                    # file overwrites by multiple extractions to same
                    # sdir.
# Also track locations where temporary installations, if necessary, of
# Algorithm::Diff and/or Regexp::Common are done.  Make sure these
# directories are not counted as inputs (ref bug #80 2012-11-23).
my %TEMP_INST = ();

# invert %Language_by_Script hash to get an easy-to-look-up list of known
# scripting languages
my %Script_Language = map { $_ => 1 } values %Language_by_Script ;
# 1}}}
# Step 2:  Early exits for display, summation. {{{1
#
print_extension_info(   $opt_show_ext     ) if defined $opt_show_ext ;
print_language_info(    $opt_show_lang, '') if defined $opt_show_lang;
print_language_filters( $opt_explain      ) if defined $opt_explain  ;
exit if (defined $opt_show_ext)  or
        (defined $opt_show_lang) or
        (defined $opt_explain)   or
        $list_no_autogen;

Top_of_Processing_Loop:
# Sorry, coding purists.  Using a goto to implement --count-and-diff
# which has to do three passes over the main code, starting with
# a clean slate each time.
if ($opt_count_diff) {
    @ARGV = ( $COUNT_DIFF_ARGV[ $opt_count_diff ] );
    if ($opt_count_diff == 3) {
        $opt_diff = 1;
        @ARGV = @{$COUNT_DIFF_ARGV[ $opt_count_diff ]}; # last arg is list of list
    } elsif ($opt_diff_list_files) {
        $opt_diff = 0;
    }
    if ($opt_report_file) {
        # Instead of just one output file, will have three.
        # Keep their names unique otherwise results are clobbered.
        # Replace file path separators with underscores otherwise
        # may end up with illegal file names.
        my ($fn_0, $fn_1) = (undef, undef);
        if ($ON_WINDOWS) {
            ($fn_0 = $ARGV[0]) =~ s{\\}{_}g;
             $fn_0 =~ s{:}{_}g;
             $fn_0 =~ s{/}{_}g;
            ($fn_1 = $ARGV[1]) =~ s{\\}{_}g if defined $ARGV[1];
             $fn_1 =~ s{:}{_}g              if defined $ARGV[1];
             $fn_1 =~ s{/}{_}g              if defined $ARGV[1];
        } else {
            ($fn_0 = $ARGV[0]) =~ s{/}{_}g;
            ($fn_1 = $ARGV[1]) =~ s{/}{_}g  if defined $ARGV[1];
        }

        if      ($opt_count_diff == 3) {
            $opt_report_file = $COUNT_DIFF_report_file . ".diff.$fn_0.$fn_1";
        } else {
            $opt_report_file = $COUNT_DIFF_report_file . ".$fn_0";
        }
    } else {
        # STDOUT; print a header showing what it's working on
        if ($opt_count_diff == 3) {
            print "\ndiff $ARGV[0] $ARGV[1]::\n";
        } else {
            print "\n" if $opt_count_diff > 1;
            print "$ARGV[0]::\n";
        }
    }
    $ALREADY_SHOWED_HEADER      = 0;
    $ALREADY_SHOWED_XML_SECTION = 0;
}

#print "Before glob have [", join(",", @ARGV), "]\n";
@ARGV = windows_glob(@ARGV) if $ON_WINDOWS;
#print "after  glob have [", join(",", @ARGV), "]\n";

# filter out archive files if requested to do so
if (defined $opt_skip_archive) {
    my @non_archive = ();
    foreach my $candidate (@ARGV) {
        if ($candidate !~ m/${opt_skip_archive}$/) {
            push @non_archive, $candidate;

        }
    }
    @ARGV = @non_archive;
}

if ($opt_sum_reports and $opt_diff) {
    my @results = ();
    if ($opt_csv and !defined($opt_csv_delimiter)) {
        $opt_csv_delimiter = ",";
    }
    if ($opt_list_file) { # read inputs from the list file
        my @list = read_list_file($opt_list_file);
        if ($opt_csv) {
            @results = combine_csv_diffs($opt_csv_delimiter, \@list);
        } else {
            @results = combine_diffs(\@list);
        }
    } elsif ($opt_vcs) { # read inputs from the VCS generator
        my @list = invoke_generator($opt_vcs, \@ARGV);
        if ($opt_csv) {
            @results = combine_csv_diffs($opt_csv_delimiter, \@list);
        } else {
            @results = combine_diffs(\@list);
        }
    } else { # get inputs from the command line
        if ($opt_csv) {
            @results = combine_csv_diffs($opt_csv_delimiter, \@ARGV);
        } else {
            @results = combine_diffs(\@ARGV);
        }
    }
    if ($opt_report_file) {
        write_file($opt_report_file, {}, @results);
    } else {
        print "\n", join("\n", @results), "\n";
    }
    exit;
}
if ($opt_sum_reports) {
    my %Results = ();
    foreach my $type( "by language", "by report file" ) {
        my $found_lang = undef;
        if ($opt_list_file or $opt_vcs) {
            # read inputs from the list file
            my @list;
            if ($opt_vcs) {
                @list = invoke_generator($opt_vcs, \@ARGV);
            } else {
                @list = read_list_file($opt_list_file);
            }
            $found_lang = combine_results(\@list,
                                           $type,
                                          \%{$Results{ $type }},
                                          \%Filters_by_Language );
        } else { # get inputs from the command line
            $found_lang = combine_results(\@ARGV,
                                           $type,
                                          \%{$Results{ $type }},
                                          \%Filters_by_Language );
        }
        next unless %Results;
        my $end_time = get_time();
        my @results  = generate_report($VERSION, $end_time - $start_time,
                                       $type,
                                      \%{$Results{ $type }}, \%Scale_Factor);
        if ($opt_report_file) {
            my $ext  = ".lang";
               $ext  = ".file" unless $type eq "by language";
            next if !$found_lang and  $ext  eq ".lang";
            write_file($opt_report_file . $ext, {}, @results);
        } else {
            print "\n", join("\n", @results), "\n";
        }
    }
    exit;
}
if ($opt_write_lang_def or $opt_write_lang_def_incl_dup) {
    my $file = $opt_write_lang_def          if $opt_write_lang_def;
       $file = $opt_write_lang_def_incl_dup if $opt_write_lang_def_incl_dup;
    write_lang_def($file                 ,
                  \%Language_by_Extension,
                  \%Language_by_Script   ,
                  \%Language_by_File     ,
                  \%Filters_by_Language  ,
                  \%Not_Code_Extension   ,
                  \%Not_Code_Filename    ,
                  \%Scale_Factor         ,
                  \%EOL_Continuation_re  ,
                  );
    exit;
}
if ($opt_show_os) {
    if ($ON_WINDOWS) {
        print "Windows\n";
    } else {
        print "UNIX\n";
    }
    exit;
}

my $max_processes = get_max_processes();

# 1}}}
# Step 3:  Create a list of files to consider. {{{1
#  a) If inputs are binary archives, first cd to a temp
#     directory, expand the archive with the user-given
#     extraction tool, then add the temp directory to
#     the list of dirs to process.
#  b) Create a list of every file that might contain source
#     code.  Ignore binary files, zero-sized files, and
#     any file in a directory the user says to exclude.
#  c) Determine the language for each file in the list.
#
my @binary_archive = ();
my $cwd            = cwd();
if ($opt_extract_with) {
#print "cwd main = [$cwd]\n";
    my @extract_location = ();
    foreach my $bin_file (@ARGV) {
        my $extract_dir = undef;
        if ($opt_sdir) {
            ++$TEMP_OFF;
            $extract_dir = "$opt_sdir/$TEMP_OFF";
            File::Path::rmtree($extract_dir) if     is_dir($extract_dir);
            File::Path::mkpath($extract_dir) unless is_dir($extract_dir);
        } else {
            $extract_dir = tempdir( CLEANUP => 1 );  # 1 = delete on exit
        }
        $TEMP_DIR{ $extract_dir } = 1 if $opt_sql or $opt_by_file;
        print "mkdir $extract_dir\n"  if $opt_v;
        print "cd    $extract_dir\n"  if $opt_v;
        chdir $extract_dir;
        my $bin_file_full_path = "";
        if (File::Spec->file_name_is_absolute( $bin_file )) {
            $bin_file_full_path = $bin_file;
#print "bin_file_full_path (was ful) = [$bin_file_full_path]\n";
        } else {
            $bin_file_full_path = File::Spec->catfile( $cwd, $bin_file );
#print "bin_file_full_path (was rel) = [$bin_file_full_path]\n";
        }
        my     $extract_cmd = uncompress_archive_cmd($bin_file_full_path);
        print  $extract_cmd, "\n" if $opt_v;
        system $extract_cmd;
        push @extract_location, $extract_dir;
        chdir $cwd;
    }
    # It is possible that the binary archive itself contains additional
    # files compressed the same way (true for Java .ear files).  Go
    # through all the files that were extracted, see if they are binary
    # archives and try to extract them.  Lather, rinse, repeat.
    my $binary_archives_exist = 1;
    my $count_binary_archives = 0;
    my $previous_count        = 0;
    my $n_pass                = 0;
    while ($binary_archives_exist) {
        @binary_archive = ();
        foreach my $dir (@extract_location) {
            find(\&archive_files, $dir);  # populates global @binary_archive
        }
        foreach my $archive (@binary_archive) {
            my $extract_dir = undef;
            if ($opt_sdir) {
                ++$TEMP_OFF;
                $extract_dir = "$opt_sdir/$TEMP_OFF";
                File::Path::rmtree($extract_dir) if     is_dir($extract_dir);
                File::Path::mkpath($extract_dir) unless is_dir($extract_dir);
            } else {
                $extract_dir = tempdir( CLEANUP => 1 );  # 1 = delete on exit
            }
            $TEMP_DIR{ $extract_dir } = 1 if $opt_sql or $opt_by_file;
            print "mkdir $extract_dir\n"  if $opt_v;
            print "cd    $extract_dir\n"  if $opt_v;
            chdir  $extract_dir;

            my     $extract_cmd = uncompress_archive_cmd($archive);
            print  $extract_cmd, "\n" if $opt_v;
            system $extract_cmd;
            push @extract_location, $extract_dir;
            unlink $archive;  # otherwise will be extracting it forever
        }
        $count_binary_archives = scalar @binary_archive;
        if ($count_binary_archives == $previous_count) {
            $binary_archives_exist = 0;
        }
        $previous_count = $count_binary_archives;
    }
    chdir $cwd;

    @ARGV = @extract_location;
} else {
    # see if any of the inputs need to be auto-uncompressed &/or expanded
    my @updated_ARGS = ();
    replace_git_hash_with_tarfile(\@ARGV, \@git_similarity) if $opt_force_git;
    foreach my $Arg (@ARGV) {
        if (is_dir($Arg)) {
            push @updated_ARGS, $Arg;
            next;
        }
        my $full_path = "";
        if (File::Spec->file_name_is_absolute( $Arg )) {
            $full_path = $Arg;
        } else {
            $full_path = File::Spec->catfile( $cwd, $Arg );
        }
#print "full_path = [$full_path]\n";
        my $extract_cmd = uncompress_archive_cmd($full_path);
        if ($extract_cmd) {
            my $extract_dir = undef;
            if ($opt_sdir) {
                ++$TEMP_OFF;
                $extract_dir = "$opt_sdir/$TEMP_OFF";
                File::Path::rmtree($extract_dir) if     is_dir($extract_dir);
                File::Path::mkpath($extract_dir) unless is_dir($extract_dir);
            } else {
                $extract_dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
            }
            $TEMP_DIR{ $extract_dir } = 1 if $opt_sql or $opt_by_file;
            print "mkdir $extract_dir\n"  if $opt_v;
            print "cd    $extract_dir\n"  if $opt_v;
            chdir  $extract_dir;
            print  $extract_cmd, "\n" if $opt_v;
            system $extract_cmd;
            push @updated_ARGS, $extract_dir;
            chdir $cwd;
        } else {
            # this is a conventional, uncompressed, unarchived file
            # or a directory; keep as-is
            push @updated_ARGS, $Arg;
        }
    }
    @ARGV = @updated_ARGS;

    # make sure we're not counting any directory containing
    # temporary installations of Regexp::Common, Algorithm::Diff
    foreach my $d (sort keys %TEMP_INST) {
        foreach my $a (@ARGV) {
            next unless is_dir($a);
            if ($opt_v > 2) {
                printf "Comparing %s (location of %s) to input [%s]\n",
                        $d, $TEMP_INST{$d}, $a;
            }
            if ($a eq $d) {
                die "File::Temp::tempdir chose directory ",
                    $d, " to install ", $TEMP_INST{$d}, " but this ",
                    "matches one of your input directories.  Rerun ",
                    "with --sdir and supply a different temporary ",
                    "directory for ", $TEMP_INST{$d}, "\n";
            }
        }
    }
}
# 1}}}
my @Errors    = ();
my @file_list = ();  # global variable updated in files()
my %Ignored   = ();  # files that are not counted (language not recognized or
                     # problems reading the file)
my @Lines_Out = ();
my %upper_lower_map = ();  # global variable (needed only on Windows) to
                           # track case of original filename, populated in
                           # make_file_list() if $ON_WINDOWS
if ($opt_diff) {
# Step 4:  Separate code from non-code files.  {{{1
my @fh            = ();
my @files_for_set = ();
my @files_added_tot = ();
my @files_removed_tot = ();
my @file_pairs_tot = ();
# make file lists for each separate argument
if ($opt_diff_list_file) {
    @files_for_set = ( (), () );
    file_pairs_from_file($opt_diff_list_file, # in
                        \@files_added_tot   , # out
                        \@files_removed_tot , # out
                        \@file_pairs_tot    , # out
                       );
    foreach my $F (@files_added_tot) {
        if ($ON_WINDOWS) {
            (my $lc = lc $F) =~ s{\\}{/}g;
            $upper_lower_map{$lc} = $F;
            $F = $lc;
        }
        push @{$files_for_set[1]}, $F;
    }
    foreach my $F (@files_removed_tot) {
        if ($ON_WINDOWS) {
            (my $lc = lc $F) =~ s{\\}{/}g;
            $upper_lower_map{$lc} = $F;
            $F = $lc;
        }
        push @{$files_for_set[0]}, $F;
    }
    foreach my $pair (@file_pairs_tot) {
        if ($ON_WINDOWS) {
            push @{$files_for_set[0]}, lc $pair->[0];
            push @{$files_for_set[1]}, lc $pair->[1];
        } else {
            push @{$files_for_set[0]}, $pair->[0];
            push @{$files_for_set[1]}, $pair->[1];
        }
    }
    @ARGV = (1, 2); # place holders
}
for (my $i = 0; $i < scalar @ARGV; $i++) {
    if ($opt_diff_list_file) {
        push @fh, make_file_list($files_for_set[$i], $i+1,
                                \%Error_Codes, \@Errors, \%Ignored);
        @{$files_for_set[$i]} = @file_list;
    } elsif ($opt_diff_list_files) {
        my @list_files = read_list_file($ARGV[$i]);
        push @fh, make_file_list(\@list_files, $i+1,
                                \%Error_Codes, \@Errors, \%Ignored);
        @{$files_for_set[$i]} = @file_list;
    } else {
        push @fh, make_file_list([ $ARGV[$i] ], $i+1,
                                \%Error_Codes, \@Errors, \%Ignored);
        @{$files_for_set[$i]} = @file_list;
    }
    if ($opt_exclude_list_file) {
        # note: process_exclude_list_file() references global @file_list
        process_exclude_list_file($opt_exclude_list_file,
                                 \%Exclude_Dir,
                                 \%Ignored);
    }
    if ($opt_no_autogen) {
        exclude_autogenerated_files(\@{$files_for_set[$i]},  # in/out
                                    \%Error_Codes, \@Errors, \%Ignored);
    }
    @file_list = ();
}
# 1}}}
# Step 5:  Remove duplicate files.             {{{1
#
my %Language           = ();
my %unique_source_file = ();
my $n_set = 0;
foreach my $FH (@fh) {  # loop over each pair of file sets
    ++$n_set;
    remove_duplicate_files($FH,
                               \%{$Language{$FH}}               ,
                               \%{$unique_source_file{$FH}}     ,
                          \%Error_Codes                         ,
                               \@Errors                         ,
                               \%Ignored                        );
    if ($opt_exclude_content) {
        exclude_by_regex($opt_exclude_content,              # in
                        \%{$unique_source_file{$FH}},       # in/out
                        \%Ignored);                         # out
    } elsif ($opt_include_content) {
        include_by_regex($opt_include_content,              # in
                        \%{$unique_source_file{$FH}},       # in/out
                        \%Ignored);                         # out
    }

    if ($opt_include_lang) {
        # remove files associated with languages not
        # specified by --include-lang
        my @delete_file = ();
        foreach my $file (keys %{$unique_source_file{$FH}}) {
            my $keep_file = 0;
            foreach my $keep_lang (keys %Include_Language) {
                if (lc($Language{$FH}{$file}) eq $keep_lang) {
                    $keep_file = 1;
                    last;
                }
            }
            next if $keep_file;
            push @delete_file, $file;
        }
        foreach my $file (@delete_file) {
            delete $Language{$FH}{$file};
        }
    }

    printf "%2d: %8d unique file%s.                          \r",
        $n_set,
        plural_form(scalar keys %unique_source_file)
        unless $opt_quiet;
}
# 1}}}
# Step 6:  Count code, comments, blank lines.  {{{1
#
my %Results_by_Language = ();
my %Results_by_File     = ();
my %Delta_by_Language   = ();
my %Delta_by_File       = ();

my %alignment = ();

my $fset_a = $fh[0];
my $fset_b = $fh[1];

my $n_filepairs_compared = 0;
my $tot_counted = 0;

if ( scalar @fh != 2 ) {
    print "Error: incorrect length fh array when preparing diff at step 6.\n";
    exit 1;
}
if (!$opt_diff_list_file) {
    align_by_pairs(\%{$unique_source_file{$fset_a}}      , # in
                   \%{$unique_source_file{$fset_b}}      , # in
                   \@files_added_tot                     , # out
                   \@files_removed_tot                   , # out
                   \@file_pairs_tot                      , # out
                  );
}

#use Data::Dumper;
#print "added : ", Dumper(\@files_added_tot);
#print "removed : ", Dumper(\@files_removed_tot);
#print "pairs : ", Dumper(\@file_pairs_tot);

if ( $max_processes == 0) {
    # Multiprocessing is disabled
    my $part = count_filesets ( $fset_a, $fset_b, \@files_added_tot,
                               \@files_removed_tot, \@file_pairs_tot,
                               0, \%Language, \%Ignored);
    %Results_by_File = %{$part->{'results_by_file'}};
    %Results_by_Language= %{$part->{'results_by_language'}};
    %Delta_by_File = %{$part->{'delta_by_file'}};
    %Delta_by_Language= %{$part->{'delta_by_language'}};
    %Ignored = ( %Ignored, %{$part->{'ignored'}});
    %alignment = %{$part->{'alignment'}};
    $n_filepairs_compared = $part->{'n_filepairs_compared'};
    push ( @Errors, @{$part->{'errors'}});
} else {
    # Multiprocessing is enabled
    # Do not create more processes than the amount of data to be processed
    my $num_processes = min(max(scalar @files_added_tot,
                                scalar @files_removed_tot,
                                scalar @file_pairs_tot),
                            $max_processes);
    # ... but use at least one process.
       $num_processes = 1
            if $num_processes == 0;
    # Start processes for counting
    my $pm = Parallel::ForkManager->new($num_processes);
    # When processes finish, they will use the embedded subroutine for
    # merging the data into global variables.
    $pm->run_on_finish ( sub {
        my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $part) = @_;
        my $part_ignored = $part->{'ignored'};
        my $part_result_by_file = $part->{'results_by_file'};
        my $part_result_by_language = $part->{'results_by_language'};
        my $part_delta_by_file = $part->{'delta_by_file'};
        my $part_delta_by_language = $part->{'delta_by_language'};
        my $part_alignment = $part->{'alignment'};
        my $part_errors = $part->{'errors'};
           $tot_counted += scalar keys %$part_result_by_file;
           $n_filepairs_compared += $part->{'n_filepairs_compared'};
        # Since files are processed by multiple processes, we can't measure
        # the number of processed files exactly. We approximate this by showing
        # the number of files counted by finished processes.
        printf "Counting:  %d\r", $tot_counted
                 if $opt_progress_rate;

        foreach my $this_language ( keys %$part_result_by_language ) {
            my $counts = $part_result_by_language->{$this_language};
            foreach my $inner_key ( keys %$counts ) {
                $Results_by_Language{$this_language}{$inner_key} +=
                    $counts->{$inner_key};
            }
        }

        foreach my $this_language ( keys %$part_delta_by_language ) {
            my $counts = $part_delta_by_language->{$this_language};
            foreach my $inner_key ( keys %$counts ) {
                my $statuses = $counts->{$inner_key};
                foreach my $inner_status ( keys %$statuses ) {
                    $Delta_by_Language{$this_language}{$inner_key}{$inner_status} +=
                          $counts->{$inner_key}->{$inner_status};
                }
            }
        }

        foreach my $label ( keys %$part_alignment ) {
            my $inner = $part_alignment->{$label};
            foreach my $key ( keys %$inner ) {
                $alignment{$label}{$key} = 1;
            }
        }

        %Results_by_File = ( %Results_by_File, %$part_result_by_file );
        %Delta_by_File = ( %Delta_by_File, %$part_delta_by_file );
        %Ignored = (%Ignored, %$part_ignored );
        push ( @Errors, @$part_errors );
    } );

    my $num_filepairs_per_part = ceil ( ( scalar @file_pairs_tot ) / $num_processes );
    my $num_filesremoved_per_part = ceil ( ( scalar @files_removed_tot ) / $num_processes );
    my $num_filesadded_per_part = ceil ( ( scalar @files_added_tot ) / $num_processes );

    while ( 1 ) {
        my @files_added_part = splice @files_added_tot, 0, $num_filesadded_per_part;
        my @files_removed_part = splice @files_removed_tot, 0, $num_filesremoved_per_part;
        my @filepairs_part = splice @file_pairs_tot, 0, $num_filepairs_per_part;
        if ( scalar @files_added_part == 0 and scalar @files_removed_part == 0 and
             scalar @filepairs_part == 0 ) {
            last;
        }

        $pm->start() and next;
        my $count_result = count_filesets ( $fset_a, $fset_b,
            \@files_added_part, \@files_removed_part,
            \@filepairs_part, 1, \%Language, \%Ignored );
        $pm->finish(0 , $count_result);
    }
    # Wait for processes to finish
    $pm->wait_all_children();
}

# Write alignment data, if needed
if ($opt_diff_alignment) {
    write_alignment_data ( $opt_diff_alignment, $n_filepairs_compared, \%alignment ) ;
}

my $separator = defined $opt_csv_delimiter ? $opt_csv_delimiter : ": ";
my @ignored_reasons = map { "${_}${separator} $Ignored{$_}" } sort keys %Ignored;
write_file($opt_ignored, {"file_type" => "ignored",
                          "separator" => ": ",
                          "columns"   => ["file", "reason"],
                         }, @ignored_reasons   ) if $opt_ignored;
write_file($opt_counted, {}, sort keys %Results_by_File) if $opt_counted;
# 1}}}
# Step 7:  Assemble results.                   {{{1
#
my $end_time = get_time();
printf "%8d file%s ignored.                           \n",
    plural_form(scalar keys %Ignored) unless $opt_quiet;
print_errors(\%Error_Codes, \@Errors) if @Errors;
if (!%Delta_by_Language) {
    print "Nothing to count.\n";
    exit;
}

if ($opt_by_file) {
    @Lines_Out = diff_report($VERSION, get_time() - $start_time,
                            "by file",
                            \%Delta_by_File, \%Scale_Factor);
} else {
    @Lines_Out = diff_report($VERSION, get_time() - $start_time,
                            "by language",
                            \%Delta_by_Language, \%Scale_Factor);
}

# 1}}}
} else {
# Step 4:  Separate code from non-code files.  {{{1
my $fh = 0;
if ($opt_list_file or $opt_diff_list_files or $opt_vcs) {
    my @list;
    if ($opt_vcs) {
        @list = invoke_generator($opt_vcs, \@ARGV);
    } elsif ($opt_list_file) {
        @list = read_list_file($opt_list_file);
    } else {
        @list = read_list_file($ARGV[0]);
    }
    $fh = make_file_list(\@list, 0, \%Error_Codes, \@Errors, \%Ignored);
} else {
    $fh = make_file_list(\@ARGV, 0, \%Error_Codes, \@Errors, \%Ignored);
    #     make_file_list populates global variable @file_list via call to
    #     File::Find's find() which in turn calls files()
}
if ($opt_exclude_list_file) {
    # note: process_exclude_list_file() references global @file_list
    process_exclude_list_file($opt_exclude_list_file,
                             \%Exclude_Dir,
                             \%Ignored);
}
if ($opt_skip_win_hidden and $ON_WINDOWS) {
    my @file_list_minus_hidden = ();
    # eval code to run on Unix without 'missing Win32::File module' error.
    my $win32_file_invocation = '
        use Win32::File;
        foreach my $F (@file_list) {
            my $attr = undef;
            Win32::File::GetAttributes($F, $attr);
            if ($attr & HIDDEN) {
                $Ignored{$F} = "Windows hidden file";
                print "Ignoring $F since it is a Windows hidden file\n"
                    if $opt_v > 1;
            } else {
                push @file_list_minus_hidden, $F;
            }
        }';
    eval $win32_file_invocation;
    @file_list = @file_list_minus_hidden;
}
if ($opt_no_autogen) {
    exclude_autogenerated_files(\@file_list,  # in/out
                                \%Error_Codes, \@Errors, \%Ignored);
}
#printf "%8d file%s excluded.                     \n",
#   plural_form(scalar keys %Ignored)
#   unless $opt_quiet;
# die print ": ", join("\n: ", @file_list), "\n";
# 1}}}
# Step 5:  Remove duplicate files.             {{{1
#
my %Language           = ();
my %unique_source_file = ();
remove_duplicate_files($fh                          ,   # in
                           \%Language               ,   # out
                           \%unique_source_file     ,   # out
                      \%Error_Codes                 ,   # in
                           \@Errors                 ,   # out
                           \%Ignored                );  # out
if ($opt_exclude_content) {
    exclude_by_regex($opt_exclude_content,              # in
                    \%unique_source_file ,              # in/out
                    \%Ignored);                         # out
} elsif ($opt_include_content) {
    include_by_regex($opt_include_content,              # in
                    \%unique_source_file ,              # in/out
                    \%Ignored);                         # out
}
printf "%8d unique file%s.                              \n",
    plural_form(scalar keys %unique_source_file)
    unless $opt_quiet;
# 1}}}
# Step 6:  Count code, comments, blank lines.  {{{1
#
my %Results_by_Language = ();
my %Results_by_File     = ();
my @results_parts  = ();
my @sorted_files = sort keys %unique_source_file;

if ( $max_processes == 0) {
    # Multiprocessing is disabled
    my $part = count_files ( \@sorted_files , 0, \%Language);
    %Results_by_File = %{$part->{'results_by_file'}};
    %Results_by_Language= %{$part->{'results_by_language'}};
    %Ignored = ( %Ignored, %{$part->{'ignored'}});
    push ( @Errors, @{$part->{'errors'}});
} else {
    # Do not create more processes than the number of files to be processed
    my $num_files = scalar @sorted_files;
    my $num_processes = $num_files >= $max_processes ? $max_processes : $num_files;
    # Use at least one process.
       $num_processes = 1
            if $num_processes == 0;
    # Start processes for counting
    my $pm = Parallel::ForkManager->new($num_processes);
    # When processes finish, they will use the embedded subroutine for
    # merging the data into global variables.
    $pm->run_on_finish ( sub {
        my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $part) = @_;
        my $part_ignored = $part->{'ignored'};
        my $part_result_by_file = $part->{'results_by_file'};
        my $part_result_by_language = $part->{'results_by_language'};
        my $part_errors = $part->{'errors'};
        my $nCounted+= scalar keys %$part_result_by_file;
        # Since files are processed by multiple processes, we can't measure
        # the number of processed files exactly. We approximate this by showing
        # the number of files counted by finished processes.
        printf "Counting:  %d\r", $nCounted
                 if $opt_progress_rate;

        foreach my $this_language ( keys %$part_result_by_language ) {
            my $counts = $part_result_by_language->{$this_language};
            foreach my $inner_key ( keys %$counts ) {
                $Results_by_Language{$this_language}{$inner_key} +=
                    $counts->{$inner_key};
            }
        }
        %Results_by_File = ( %Results_by_File, %$part_result_by_file );
        %Ignored = (%Ignored, %$part_ignored);
        push ( @Errors, @$part_errors);
    } );
    my $num_files_per_part = ceil ( ( scalar @sorted_files ) / $num_processes );
    while ( my @part = splice @sorted_files, 0 , $num_files_per_part ) {
        $pm->start() and next;
        my $count_result = count_files ( \@part, 1, \%Language );
        $pm->finish(0 , $count_result);
    }
    # Wait for processes to finish
    $pm->wait_all_children();
}

my $separator = defined $opt_csv_delimiter ? $opt_csv_delimiter : ": ";
my @ignored_reasons = map { "${_}${separator} $Ignored{$_}" } sort keys %Ignored;
write_file($opt_ignored, {"file_type" => "ignored",
                          "separator" => $separator,
                          "columns"   => ["file", "reason"],
                         }, @ignored_reasons   ) if $opt_ignored;
if ($opt_summary_cutoff) {
    %Results_by_Language = apply_cutoff($opt_summary_cutoff,
                                       \%Results_by_Language);
}
write_file($opt_counted, {}, sort keys %Results_by_File) if $opt_counted;
# 1}}}
# Step 7:  Assemble results.                   {{{1
#
my $end_time = get_time();
printf "%8d file%s ignored.\n", plural_form(scalar keys %Ignored)
    unless $opt_quiet;
print_errors(\%Error_Codes, \@Errors) if @Errors;
if (!%Results_by_Language) {
    write_null_results($opt_json, $opt_xml, $opt_report_file);
    exit;
}

generate_sql($end_time - $start_time,
            \%Results_by_File, \%Scale_Factor) if $opt_sql;

exit if $skip_generate_report;
if      ($opt_by_file_by_lang) {
    push @Lines_Out, generate_report( $VERSION, $end_time - $start_time,
                                      "by file",
                                      \%Results_by_File,    \%Scale_Factor);
    push @Lines_Out, generate_report( $VERSION, $end_time - $start_time,
Loading
Loading full blame...