// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Count {
    private static class Code {
        private int nfiles;
        private int nlines;
        public Code() {
            nfiles = 0;
            nlines = 0;
        }
        public int getNfiles() {
            return nfiles;
        }
        public void addFile() {
            nfiles++;
        }
        public int getNlines() {
            return nlines;
        }
        public void addLines(int n) {
            nlines += n;
        }
    }
    private static int count(File f) throws IOException {
        int n = 0;
        BufferedReader br = new BufferedReader(new FileReader(f));
        String line;
        while((line = br.readLine()) != null) n++;
        br.close();
        return n;
    }
    private static void recurse(File dir, String[] exts, Code code) throws IOException {
        for(File f : dir.listFiles()) {
            if(f.isDirectory()) {
                recurse(f, exts, code);
            } else {
                for(String ext : exts) {
                    if(f.getName().endsWith(ext)) {
                        code.addFile();
                        code.addLines(count(f));
                    }
                }
            }
        }
    }
    private static void count(String dir, String[] exts) throws IOException {
        String crit = "";
        for(String ext : exts) crit = crit + (crit.length() > 0 ? "," : "") + ext;
        Code code = new Code();
        recurse(new File(dir), exts, code);
        System.out.printf("%s (%s): %d files with %d lines%n", dir, crit, code.getNfiles(), code.getNlines());
    }
    public static void main(String[] args) throws Exception {
        count("../..", new String[] { ".h", ".c"});
        count("../..", new String[] { ".java", ".jsp"});
    }
}
