File: grepx.pl

package info (click to toggle)
arb 6.0.6-8
  • links: PTS, VCS
  • area: non-free
  • in suites: sid, trixie
  • size: 66,204 kB
  • sloc: ansic: 394,911; cpp: 250,290; makefile: 19,644; sh: 15,879; perl: 10,473; fortran: 6,019; ruby: 683; xml: 503; python: 53; awk: 32
file content (854 lines) | stat: -rwxr-xr-x 25,838 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
#!/usr/bin/perl
# ======================================================================== #
#                                                                          #
#   File      : grepx.pl                                                   #
#   Purpose   : Replacement for grep (used from emacs)                     #
#                                                                          #
#   (C) November 2005 by Ralf Westram                                      #
#                                                                          #
#   Permission to use, copy, modify, distribute and sell this software     #
#   and its documentation for any purpose is hereby granted without fee,   #
#   provided that the above copyright notice appear in all copies and      #
#   that both that copyright notice and this permission notice appear      #
#   in supporting documentation.                                           #
#                                                                          #
#   Ralf Westram makes no representations about the suitability of this    #
#   software for any purpose.  It is provided "as is" without express or   #
#   implied warranty.                                                      #
#                                                                          #
# ======================================================================== #
#
# Improvements compared with grep:
#
# * prints line column information
# * knows about groups of files belonging together (e.g. *.cxx *.hxx)
# * knows about special file locations (e.g. emacs lisp code, /usr/include, ...)
# * able to search complete CVS/SVN trees
# * some ARB specific specials
#
# --------------------------------------------------------------------------------

use strict;
use warnings;
use Cwd;

# --------------------------------------------------------------------------------

my $tabsize = 4; # specify your emacs tabsize here (used to correct column position)

# --------------------------------------------------------------------------------
# group definitions (you may want to change here):
#
# Each element in groups defines a cluster of files.
# One cluster consists of:
#
# [0] = ref to array of header extensions
# [1] = ref to array of normal extensions
# [2] = ref to array of add. directories to search for
# [3] = ref to array of add. extensions to search
#
# If extension given is member of [0] (or [1] if not -h given) of a cluster,
# then the cluster gets activated (we call this an AC). Extensions in [3] do
# NOT activate clusters!
#
# If -h is given, only extensions from [0] of all ACs are searched
# otherwise those from [1] and [3] are added. ([3] is todo!)
#
# If -g is given the add. directories from [2] of all ACs are searched as well.


my @groups = (
              # C/C++
              [
               [ '.hxx', '.hpp', '.hh', '.h' ], # header files
               [ '.cxx', '.cpp', '.cc', '.c' ], # code files
               [
                '/usr/include',
                '/usr/include/X11',
                '/usr/include/g++',
                '/usr/include/sys',
               ], # additional header directories (used with -g)
               [ '.aisc', '.pa' ],
              ],
              # ARB code generation
              [
               [ ],
               [ '.aisc', '.pa' ],
               [ ],
               [ '.cxx', '.cpp', '.cc', '.c', '.hxx', '.hpp', '.hh', '.h' ],
              ],
              # perl
              [
               [ '.pm' ],                       # header files
               [ '.pl', '.cgi' ],               # code files
               [ '/usr/lib/perl5' ],            # additional header directories (used with -g)
              ],
              # java
              [
               [ ],            # java sucks headers
               [ '.java' ],
              ],
              # xml development
              [
               [ '.dtd' ],
               [ '.xml', '.xsl' ],
              ],
              # lisp
              [
               [ ],
               [ '.el' ],
               [
                '/usr/share/emacs/site-lisp',
                '/usr/share/xemacs',
               ],
              ],
              # shell-scripts etc.
              [
               [ ],
               [ '.sh', '.cmd', '.bat' ],
              ],
              # text files
              [
               [ ],
               [ '.txt', '.readme' ],
              ],
              # html etc
              [
               [ ],
               [ '.html', '.htm' ],
              ],
              # hamster scripts
              [
               [ '.hsm' ],
               [ '.hsc' ],
               [ ], # no add. directories
               [ '.ini' ], # search add. but don't add cluster if included
              ],
              # Euphoria
              [
               [ '.e' ],
               [ '.exw' ],
              ],
              # ARB specifics
              [ # anything where aci/srt commands occur
               [ ],
               [ '.menu', '.source', '.hlp', '.eft', '.ift', '.mask', '.sellst' ],
               [ ],
               [ '.c', '.cxx' ],
              ],
              );

# files always searched (not by 'same' and 'header' search)
my @normally_searches = ( 'makefile' );

# files always searched by global search
my @global_always_searches = ( );

# --------------------------------------------------------------------------------

my $global           = 0;
my $headers_only     = 0;
my $same_ext_only    = 0;
my $ignore_case      = 0;
my $recurse_subdirs  = 0;
my $one_hit_per_line = 0;
my $verbose          = 0;
my $matchFiles       = 1;
my $arbSpecials      = 0;
my $maxhits          = undef; # undef means unlimited
my $searchNonCVS     = 0;

my $extension       = undef;
my $use_as_wildcard = 0;
my $regexpr         = undef;

my $calldir  = cwd();
my $startdir = undef;

# --------------------------------------------------------------------------------

my $GSM_NONE   = 0;
my $GSM_CVS    = 1; # scan a CVS/SVN tree
my $GSM_PARENT = 2; # do a simple parent scan

my $global_scan_mode = $GSM_NONE;

# --------------------------------------------------------------------------------

sub shall_skip_file($) {
  my ($file) = @_;
  die "arbSpecials not 1" if ($arbSpecials!=1);
  if ($file =~ /PERL2ARB\//o) {
    my $rest = $';
    if ($rest eq 'ARB.c' or $rest eq 'proto.h') { return 1; }
  }
  elsif ($file =~ /lib\/help\//o) {
    return 1;
  }
  return 0;
}

# --------------------------------------------------------------------------------

my @ignores = (); # directory local excludes (reg.expressions)
my $ignoreCount = 0; # overall ignore count

sub forget_grepxignore() { @ignores = (); }

sub load_grepxignore($) {
  my ($grepxignore) = @_;

  @ignores = ();
  open(IGNORE,'<'.$grepxignore) || die "can't open '$grepxignore' (Reason: $!)";
  foreach (<IGNORE>) {
    chomp;
    push @ignores, qr/^$_$/;
  }
  close(IGNORE);
}

sub is_ignored($) {
  my ($name) = @_;
  foreach (@ignores) {
    if ($name =~ $_) {
      $verbose==0 || print "Ignoring '$name' (by $_)\n";
      $ignoreCount++;
      return 1;
    }
  }
  return 0;
}

# --------------------------------------------------------------------------------

my $reg_nameOnly  = qr/\/([^\/]+)$/;
my $reg_extension = qr/(\.[^\.]+)$/;
# (\.[^\.]+)

my ($IS_HEADER,$IS_NORMAL,$IS_OTHER,$IS_ADDITIONAL) = (4,3,2,1);

my %wanted_extensions = ();
my %wanted_files      = (); # files that are always searched

my @add_header_dirs = ();

my $reg_is_cpp_std_dir = qr/^\/usr\/include\/g\+\+(\/|$)/;

sub shall_search_file($$) {
  my ($file,$indir) = @_;

  if ($use_as_wildcard==0) {
    if ($file =~ $reg_nameOnly) { $file = $1; } # behind last /

    if ($file =~ /^\.?\#/ or $file =~ /~$/) { return 0; } # skip backup files etc.

    my $ext = '';
    if ($file =~ $reg_extension) { $ext = $1; }

    if ($ext eq '') {
      if ($indir =~ $reg_is_cpp_std_dir) {
        # print "hack: considering $file in $indir\n";
        $ext = '.h'; # special hack for new style C++ header (they suck an extension)
      }
      else {
        if (not $haveFile) { return 0; }
        my $full = $indir.'/'.$file;
        my $type = `file $full`; # detect filetype
        chomp $type;
        if ($type =~ /^[^:]+: (.*)/o) {
          $type = $1;
          if ($type =~ /shell.*script/o) { $ext = '.sh'; }
          elsif ($type =~ /perl.*script/o) { $ext = '.pl'; }
          elsif ($type =~ /ASCII.*text/o) { $ext = '.txt'; }
          elsif ($type =~ /ISO.*text/o) { $ext = '.txt'; }
          elsif ($type =~ /executable/o) { ; }
          elsif ($type =~ /symbolic.link.to/o) { ; }
          else {
            print "Unhandled file='$full'\n        type='$type'\n";
          }
        }
      }
    }

    $ext = lc($ext);
    if (exists $wanted_extensions{$ext}) { return NotIgnored($file,$wanted_extensions{$ext}); }

    $file = lc($file);
    if (exists $wanted_files{$file}) { return NotIgnored($file,$IS_OTHER); }
  }
  else {
    if ($file =~ /$extension/ig) {
      return NotIgnored($file,$IS_NORMAL);
    }
  }

  return 0;
}

sub memberOf($\@) {
  my ($ext, $extArray_r) = @_;
  foreach (@$extArray_r) {
    if ($ext eq $_) { return 1; }
  }
  return undef;
}

sub add_files(\@$) {
  my ($ext_array_r,$value) = @_;
  foreach (@$ext_array_r) { $wanted_extensions{$_} = $value; }
}

sub init_wanted() {
  %wanted_extensions = ();
  %wanted_files      = ();

  if ($same_ext_only==0 and $headers_only==0) {
    foreach (@normally_searches) { $wanted_files{$_} = 1; }
  }
  if ($global==1) {
    foreach (@global_always_searches)  { $wanted_files{$_} = 1; }
  }

  if ($same_ext_only) {
    $wanted_extensions{$extension} = $IS_NORMAL;
  }
  elsif ($extension eq '') {
    foreach my $group_r (@groups) {
      my $header_r  = $$group_r[0];
      my $nheader_r = $$group_r[1];

      add_files(@$header_r, $IS_HEADER);
      if ($headers_only==0) { add_files(@$nheader_r, $IS_NORMAL); }
    }
    my $which = '';
    if ($headers_only==1) { $which = 'header-'; }
    print "grepx: No extension given - searching all known ".$which."extensions.\n";
  }
  else {
    my $found_class = 0;
    my $group_count = 0;
    eval {
      foreach my $group_r (@groups) {
        my $group_defs = scalar(@$group_r);
        if ($group_defs<2) { die "Not enough entries (min. 2 are expected)"; }

        my $header_r  = $$group_r[0];
        my $nheader_r = $$group_r[1];

        if (memberOf($extension, @$header_r) or memberOf($extension, @$nheader_r)) { # is group active?
          $verbose==0 || print "'$extension' found in [@$header_r] or [@$nheader_r] - adding tables\n";
          $found_class = 1;

          add_files(@$header_r, $IS_HEADER);
          if ($headers_only==0) { add_files(@$nheader_r, $IS_NORMAL); }

          # 3rd entry is array of directories for -h -g
          if ($group_defs>=3) {
            my $add_dir_r = $$group_r[2];
            foreach my $adir (@$add_dir_r) {
              if (-d $adir) { push @add_header_dirs, $adir; }
              else { print "grepx: No such directory '$adir'\n"; }
            }

            if ($group_defs>=4) {
              my $add_extensions_r = $$group_r[3];
              if ($verbose>0) {
                print "Adding add. extensions:";
                foreach (@$add_extensions_r) { print " $_"; }
                print "\n";
              }
              add_files(@$add_extensions_r, $IS_ADDITIONAL);
            }
          }
        }
        $group_count++;
      }
    };
    if ($@) { die "Error parsing \@groups[$group_count]: $@"; }

    if ($found_class==0) {
      print "grepx: No class defined for '$extension' .. searching only '$extension' files\n";
      $wanted_extensions{$extension} = $IS_NORMAL;
    }
  }

  if ($verbose==1) {
    print "grepx: Searching";
    foreach (keys %wanted_extensions) { print " *$_"; }
    foreach (keys %wanted_files) { print " $_"; }
    print "\n";
  }

}

# --------------------------------------------------------------------------------

sub print_usage() {
  print "Usage: grepx 'ext' 'regexpr'\n".
    "Options:\n".
    " -g -> search globally (smart detect what global means)\n".
    " -h -> search in header files only (depends on 'ext')\n".
    " -s -> search in same fileextension only (default is to search file group)\n".
    " -i -> ignore case\n".
    " -r -> recurse subdirs\n".
    " -o -> one hit per line (default is to report multiple hits)\n".
    " -v -> be verbose (for debugging)\n".
    " -n -> don't match filenames\n".
    " -A -> do ARB specials if \$ARBHOME is defined\n".
    " -m xxx -> report max. xxx hits\n".
    " -c     -> search in non-CVS/SVN files as well (default is to search CVS/SVN controlled files only)".
    "\n".
    " 'ext'     extension of file where grepx is called from\n".
    " 'regexpr' perl regular expression\n\n";
}

# --------------------------------------------------------------------------------

sub parse_args() {
  my $args         = scalar(@ARGV);
  my @non_opt_args = ();
  my $ap           = 0;

  while ($ap<$args) {
    if ($ARGV[$ap] =~ /^-/) {
      my $option = $';
      if ($option eq 'g') { $global = 1; }
      elsif ($option eq 'h') { $headers_only = 1; }
      elsif ($option eq 's') { $same_ext_only = 1; }
      elsif ($option eq 'i') { $ignore_case = 1; }
      elsif ($option eq 'r') { $recurse_subdirs = 1; }
      elsif ($option eq 'o') { $one_hit_per_line = 1; }
      elsif ($option eq 'v') { $verbose = 1; }
      elsif ($option eq 'n') { $matchFiles = 0; }
      elsif ($option eq 'A') {
        if (exists $ENV{'ARBHOME'}) { $arbSpecials = 1; }
        else { print "grepx: Ignoring -A (ARBHOME not set)"; }
      }
      elsif ($option eq 'm') { $maxhits = int($ARGV[++$ap]); }
      elsif ($option eq 'c') { $searchNonCVS = 1; }
      else { die "Unknown option '-$option'\n"; }
    }
    else {
      if ($ARGV[$ap] ne '/dev/null') {
        push @non_opt_args, $ARGV[$ap];
      }
    }
    $ap++;
  }

  my $restargs = scalar(@non_opt_args);
  # print "\@non_opt_args=@non_opt_args\n";
  if ($restargs!=2) { die "Expected exactly two normal arguments (non-switches), found $restargs\n"; }

  $extension = $non_opt_args[0];
  $regexpr   = $non_opt_args[1];
  $verbose==0 || print "grepx: Using regular expression '$regexpr'\n";

  if ($ignore_case==1) { $regexpr = qr/$regexpr/i; }
  else { $regexpr = qr/$regexpr/; }

  if ($headers_only==1 and $same_ext_only==1) { die "Options -s and -h may not be used together\n"; }
}

# --------------------------------------------------------------------------------

sub pos_correction($$) {
  my ($line,$pos) = @_;
  my $prematch = substr($line,0,$pos);
  $prematch =~ s/[^\t]//go;
  return length($prematch)*($tabsize-1);
}

my $lines_examined = 0;
my $reg_startdir = undef;

sub grepfile($$\$) {
  my ($file,$entering,$entering_shown_r) = @_;

  my $matches  = 0;
  my $reported = 0;
  my $show     = $file;

  if ($file =~ $reg_startdir) { $show = $'; }

  open(FILE,"<$file") || die "can't read file '$file' (Reason: $!)";
  while (my $line = <FILE>) {
    if ($line =~ $regexpr) {
      if ((not defined $maxhits) or ($maxhits>0)) {
        my $rest   = $';
        my $hitlen = $+[0] - $-[0];
        my $pos;

        $hitlen>0 || die "Non-positive hitlen (=$hitlen) [1]";

        if ($#+ > 0) { # regexpr has subgroups -> point to start of first subgroup
          $pos = $-[$#+] + 1; # start of first subgroup
        }
        else {
          $pos = $-[0] + 1; # start of regexpr
        }

        if ($matches==0 and $arbSpecials==1) {
          if (shall_skip_file($file)==1) {
            print "grepx: Unlisted occurrence(s) in $file\n";
            return (0,0);
          }
        }

        my $correct = pos_correction($line,$pos);
        $line =~ s/\r//o;
        $line =~ s/\n//o;
        chomp($line);
        $pos += $correct;
        $line =~ s/^([\s\t]+)//o;
        my $hits = 1;

        if ($one_hit_per_line==0) {
          if ($$entering_shown_r==0) { $$entering_shown_r=1; print $entering; }
          print "$show:$.:$pos:        $line\n";
          $rest =~ s/\r//o;
          $rest =~ s/\n//o;
          chomp($rest);

          while ($rest =~ $regexpr) {
            my $start_pos = $pos+$hitlen-1;

            $start_pos >= 0 || die "Negative start_pos(=$start_pos, pos=$pos, hitlen=$hitlen)";

            $hitlen = $+[0] - $-[0];
            $hitlen>0 || die "Non-positive hitlen (=$hitlen) [2]";

            if ($#+ > 0) {
              $pos = $-[$#+] + 1;
            }
            else {
              $pos = $-[0] + 1;
            }
            $correct = pos_correction($rest,$pos);
            $pos += $start_pos+$correct;

            $pos >= 0 || die "Negative pos";

            if ($$entering_shown_r==0) { $$entering_shown_r=1; print $entering; }
            print "$show:$.:$pos: [same] $line\n";
            $hits++;
            $rest = $';
          }
        }
        else {
          if ($$entering_shown_r==0) { $$entering_shown_r=1; print $entering; }
          print "$show:$.:$pos: $line\n";
        }

        $reported += $hits;
        if (defined $maxhits) { $maxhits -= $hits; }
      }
      $matches++;
    }
    $lines_examined++;
  }
  close(FILE);
  return ($matches,$reported);
}

# --------------------------------------------------------------------------------

my $versionControl = '<unknown version control>';

sub CVS_controlled($) {
  my ($dir)       = @_;
  my $SVN_entries = $dir.'/.svn/entries';
  if (-f $SVN_entries) {
    $versionControl = 'subversion';
    1;
  }
  else {
    my $CVS_Repository = $dir.'/CVS/Repository';
    if (-f $CVS_Repository) {
      $versionControl = 'CVS';
      1;
    }
    else {
      0;
    }
  }
}

sub parent_directory($) {
  my ($dir) = @_;
  if ($dir =~ /\/[^\/]+$/) {
    return $`;
  }
  return undef;
}

# --------------------------------------------------------------------------------

sub collect_files($\%$$);
sub collect_files($\%$$) {
  my ($dir,$files_r,$is_additional_directory,$follow_file_links) = @_;

  my @files   = ();
  my @subdirs = ();

  opendir(DIR, $dir) || die "can't read directory '$dir' (Reason: $!)";
  foreach (readdir(DIR)) {
    if ($_ ne '.' and $_ ne '..') {
      my $full = $dir.'/'.$_;
      if (-l $full and ($follow_file_links==0 or -d $full)) { $verbose==0 || print "Skipping $full (symbolic link)\b"; }
      elsif (-f $full) { push @files, $full; }
      elsif (-d $full) { push @subdirs, $full; }
      else { $verbose==0 || print "Skipping $full (not a file or directory)\n"; }
    }
  }
  closedir(DIR);

  my $grepxignore = $dir.'/.grepxignore';
  if (-f $grepxignore) { load_grepxignore($grepxignore); }
  else { forget_grepxignore(); }

  foreach (@files) {
    my $shall = shall_search_file($_,$dir);
    if ($shall) {
      $verbose==0 || print "Searching $_\n";
      # $matches += grepfile($_);
      # $searched++;
      $$files_r{$_} = $shall;
    }
    else {
      $verbose==0 || print "Skipping '$_' (unwanted)\n";
    }
  }

  if ($recurse_subdirs==1) {
    my @descent_into = ();

    foreach (@subdirs) {
      my $descent = 1;
      my $reason = 'not specified';
      if ($global_scan_mode==$GSM_CVS and not $is_additional_directory and not CVS_controlled($_)) {
        if ($arbSpecials==1 and $_ =~ /\/GEN[CH]$/) {
          $verbose==0 || print "Descending non-$versionControl dir '$_' (caused by ARB mode)\n";
        }
        else {
          $descent = 0;
          $reason = 'not version-controlled';
        }
      }

      if ($descent==1) {
        $descent = NotIgnored($_,1);
        if ($descent==0) { $reason = 'Excluded by .grepxignore'; }
      }

      if ($descent==1) {
        push @descent_into, $_;
      }
      else {
        $verbose==0 || print "Skipping subdirectory '$_' ($reason)\n";
      }
    }

    foreach (@descent_into) {
      collect_files($_, %$files_r, $is_additional_directory,$follow_file_links);
    }
  }
}

sub grep_collected_files(\%$) {
  my ($files_r,$entering) = @_;

  my $entering_shown = 0;

  my %depth = map {
    my $d = $_;
    $d =~ s/[^\/\\]//ig;
    $_ => length($d);
  } keys %$files_r;

  my @files = sort {
    my $cmp = $$files_r{$b} <=> $$files_r{$a}; # file importance
    if ($cmp==0) {
      $cmp = $depth{$a} <=> $depth{$b}; # depth in directory tree
      if ($cmp==0) {
        $cmp = $a cmp $b; # alphabetically
      }
    }
    return $cmp;
  } keys %$files_r;

  my $searched = scalar(@files);
  my $matches  = 0;
  my $reported = 0;

  if ($matchFiles==1) {
    my @matching_files = ();    # files were regexp matches filename
    my $reg_name = qr/\/([^\/]+)$/;

    foreach (@files) {
      if ($_ =~ $reg_name) { # match the name part
        if ($1 =~ $regexpr) { push @matching_files, $_; }
      }
      else { die "can't parse name from '$_'"; }
    }
    my $matching_files = scalar(@matching_files);
    if ($matching_files>0) {
      print "grepx: Some filenames match your expression:\n";
      foreach (@matching_files) {
        my $show = $_;
        if ($_ =~ $reg_startdir) { $show = $'; }
        if ($entering_shown==0) { $entering_shown=1; print $entering; }
        print "$show:0: <filename matched>\n";
      }
    }
  }

  # print "grepx: Searching $searched files..\n";
  foreach (@files) {
    $verbose==0 || print "searching '$_' (depth=$depth{$_}, importance=$$files_r{$_})\n";
    my ($m,$r) = grepfile($_,$entering,$entering_shown);
    $matches += $m;
    $reported += $r;
  }


  return ($searched,$matches,$reported);
}

sub perform_grep($$$) {
  my ($startdir, $is_additional_directory, $follow_file_links) = @_;
  my %files = (); # key=file, value=file-importance
  collect_files($startdir,%files,$is_additional_directory,$follow_file_links);

  my $max_importance = -1;
  foreach (values %files) {
    if ($_ > $max_importance) { $max_importance = $_; }
  }

  if ($max_importance<=$IS_OTHER) {
    print "grepx: Only found files with importance==$max_importance (aborting)\n";
    %files = ();
  }

  my ($searched,$matches,$reported) = (0,0,0);
  if (scalar(%files)) {
    my $entering                   = "grepx: Entering directory `$startdir'\n";
    ($searched,$matches,$reported) = grep_collected_files(%files,$entering);
    if ($reported>0) { print "grepx: Leaving directory `$startdir'\n"; }
  }
  return ($searched,$matches,$reported);
}

sub grep_add_directories() {
  my ($searched,$matches,$reported) = (0,0,0);
  foreach (@add_header_dirs) {
    my ($s,$m,$r) = perform_grep($_,1,0);
    ($searched,$matches,$reported) = ($searched+$s,$matches+$m,$reported+$r);
  }
  return ($searched,$matches,$reported);
}

# --------------------------------------------------------------------------------


sub detect_wanted_startdir($) {
  my ($calldir) = @_;
  if ($global==1) {
    my $know_whats_global = 0;

    if (CVS_controlled($calldir)) {
      my $updir = parent_directory($calldir);
      while (defined $updir and -d $updir and CVS_controlled($updir)) {
        $calldir = $updir;
        $updir   = parent_directory($updir);
      }
      print "grepx: Starting global search from root of $versionControl controlled directory-tree\n";
      $global_scan_mode  = $GSM_CVS;
      $know_whats_global = 1;
    }

    if ($know_whats_global==0) {
      print "grepx: Don't know what 'global search' means here.. using parent directory\n";
      $global_scan_mode = $GSM_PARENT;
      my $updir         = parent_directory($calldir);
      if (defined $updir and -d $updir) { $calldir = $updir; }
    }
  }
  return $calldir;
}

sub megagiga($) {
  my ($val) = @_;
  if ($val<1024) { return "$val "; }

  my $pot = 0;
  while ($val>=1024) {
    $val = int($val/1024+0.5);
    $pot++;
  }
  return "$val ".substr("kMGTP", $pot-1, 1);
}

# --------------------------------------------------------------------------------

eval {
  my $start_time = time;
  parse_args();

  $startdir = detect_wanted_startdir($calldir);
  $reg_startdir = quotemeta($startdir.'/');
  $reg_startdir = qr/^$reg_startdir/;

  init_wanted();

  my ($searched,$matches,$reported) = perform_grep($startdir,0,0);
  if ($matches==0) {
    print "grepx: No results - retry with links..\n";
    ($searched,$matches,$reported) = perform_grep($startdir,0,1); # retry following links
  }

  if ($global==1 and scalar(@add_header_dirs)>0) {
    if ($reported==$matches) {
      print "grepx: ------------------------------ Searching in add. directories:\n";
      my ($s,$m,$r) = grep_add_directories();
      ($searched,$matches,$reported) = ($searched+$s,$matches+$m,$reported+$r);
    }
    else {
      print "grepx: Skipping search of add. directories - already got enough matches.\n";
    }
  }

  if ($searched == 0) {
    print "grepx: No files matched.\n";
    print "grepx: Retrying using '$extension' as wildcard.\n";

    $use_as_wildcard     = 1;
    ($searched,$matches,$reported) = perform_grep($startdir,0,0);
    if ($matches==0) {
      print "grepx: No results - retry with links..\n";
      ($searched,$matches,$reported) = perform_grep($startdir,0,1);  # retry following links
    }
    if ($searched == 0) { print "grepx: No files matched.\n"; }
  }

  if ($searched>0) {
    my $info = "Searched $searched files (".megagiga($lines_examined)."LOC). ";
    if ($matches>0) {
      if ($reported == $matches) { $info .= "Found $matches"; }
      else { $info .= "Reported $reported (of $matches found)"; }
      $info .= " matches in ".(time-$start_time)." seconds.";
    }
    else { $info .= "No matches were found."; }
    print "grepx: $info\n";
  }

  if ($ignoreCount>0) {
    print "grepx: excluded by .grepxignore: $ignoreCount files/directories\n";
  }
};
if ($@) {
  print_usage();
  die "Error: $@";
}

# --------------------------------------------------------------------------------