did a bit of flattening, but I really should name those functions soon;
added input and output files for sample data;
minor tweak;
converted the inner loop from iterative to recursive;