﻿#!/usr/bin/env perl

#############################################################
# File            : dir2csv.pl
# Input values    : None
# Purpose         : A quick hack script that reads
#                 : directories of text files into in a CSV.
# Author          : Kris Davidson (http://krisdavidson.org/)
#############################################################

use strict;
use Config::Directory;
use Text::CSV_XS;

die "usage: dir2csv <directory>\n" unless @ARGV == 1;
die "'$ARGV[0]' is not a directory\n" unless -d $ARGV[0];

my $dir = Config::Directory->new( $ARGV[0], { chomp => 0, trim => 0 })
    or die "Load of directory '$ARGV[0]' failed: $!";

my $csv = Text::CSV_XS->new;

open(CSVFILE, ">>", "/home/kris/temp.csv") or die "Couldn't open: $!"; # Hardcoded path I know, I'm lazy.

for my $file (sort keys %$dir) {
    # I am standards compliant this <BR> is not related to HTML in any way.
    my @paragraphs = map { s/\n/<BR>/g; $_ } split /\n\n+/, $dir->{$file};
    $csv->combine( $paragraphs[0], $paragraphs[1], join("<BR><BR>", @paragraphs[1..$#paragraphs]) )
        or die "combine failed: " . $csv->error_input;
    my $output = $csv->string . ","; # This is a bit ugly but its a quick hack so what do you expect.
    print CSVFILE $output;
    print CSVFILE "\n";
}

print CSVFILE "\n";
close FILE;
