Index: /main/trunk/greenstone2/perllib/plugins/CSVFieldSeparator.pm
===================================================================
--- /main/trunk/greenstone2/perllib/plugins/CSVFieldSeparator.pm	(revision 34249)
+++ /main/trunk/greenstone2/perllib/plugins/CSVFieldSeparator.pm	(revision 34249)
@@ -0,0 +1,112 @@
+##########################################################################
+#
+# CSVFieldSeparator -- helper plugin that 'auto' works out what the 
+#                      comma-separated field character is
+#
+# A component of the Greenstone digital library software
+# from the New Zealand Digital Library Project at the 
+# University of Waikato, New Zealand.
+#
+# Copyright (C) 2019 New Zealand Digital Library Project
+#
+# 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.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+#
+###########################################################################
+
+package CSVFieldSeparator;
+
+use PrintInfo;
+
+use strict;
+no strict 'refs'; # make an exception so we can use variables as filehandles
+
+BEGIN {
+    @CSVFieldSeparator::ISA = ('PrintInfo');
+}
+
+my $arguments = 
+    [ 
+      { 'name' => "csv_field_separator",
+	'desc' => "{CSVFieldSeparator.csv_field_separator}",
+	'type' => "string",
+	'deft' => "auto",
+	'reqd' => "no" },
+      { 'name' => "metadata_value_separator",
+	'desc' => "{CSVFieldSeparator.metadata_value_separator}",
+	'type' => "string",
+	'deft' => "",
+	'reqd' => "no" }
+    ];
+
+my $options = { 'name' => "CSVFieldSeparator",
+		'desc' => "{CSVFieldSeparator.desc}",
+		'abstract' => "yes",
+		'inherits' => "yes",
+		'args' => $arguments };
+
+sub new {
+    my ($class) = shift (@_);
+    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
+    push(@$pluginlist, $class);
+
+    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
+    push(@{$hashArgOptLists->{"OptList"}},$options);
+
+    my $self = new PrintInfo($pluginlist, $inputargs, $hashArgOptLists, 1);
+  
+    return bless $self, $class;
+
+}
+
+
+sub resolve_auto
+{
+    my ($self) = shift @_;
+    my ($line,$plugin_name) = @_;
+ 
+    my $outhandle = $self->{'outhandle'};
+    my $verbosity = $self->{'verbosity'};
+
+    # count number of char matches for common separates such as ',' ';' '\t' and '|'
+    my $comma_count = () = ($line =~ m/,/g);
+    my $separate_char = ",";
+    my $max_count = $comma_count; 
+    
+    my $semicolon_count = () = ($line =~ m/\;/g);
+    if ($semicolon_count > $max_count) {
+	$separate_char = ";";
+	$max_count = $semicolon_count;
+    }
+
+    my $tab_count       = () = ($line =~ m/\t/g);
+    if ($tab_count > $max_count) {
+	$separate_char = "\t";
+	$max_count = $tab_count;
+    }
+
+    my $pipe_count      = () = ($line =~ m/\|/g);
+    if ($pipe_count > $max_count) {
+	$separate_char = "|";
+	$max_count = $pipe_count;
+    }
+    
+    if ($outhandle) {
+	print $outhandle "$plugin_name: Auto selecting '$separate_char' as -separate_char\n" if ($verbosity) > 1;
+    }
+
+    return $separate_char;
+}
+
+1;
Index: /main/trunk/greenstone2/perllib/plugins/CSVPlugin.pm
===================================================================
--- /main/trunk/greenstone2/perllib/plugins/CSVPlugin.pm	(revision 34248)
+++ /main/trunk/greenstone2/perllib/plugins/CSVPlugin.pm	(revision 34249)
@@ -27,19 +27,22 @@
 package CSVPlugin;
 
-
 use SplitTextFile;
 use MetadataRead;
+use CSVFieldSeparator;
+
 use strict;
 no strict 'refs'; # allow filehandles to be variables and viceversa
 
+use Text::CSV;
 
 # CSVPlugin is a sub-class of SplitTextFile.
 sub BEGIN {
-    @CSVPlugin::ISA = ('MetadataRead', 'SplitTextFile');
+    @CSVPlugin::ISA = ('MetadataRead', 'SplitTextFile', 'CSVFieldSeparator');
 }
 
 
 my $arguments = 
-    [ { 'name' => "process_exp",
+    [ 
+      { 'name' => "process_exp",
 	'desc' => "{BaseImporter.process_exp}",
 	'type' => "regexp",
@@ -84,4 +87,5 @@
     push(@{$hashArgOptLists->{"OptList"}}, $options);
 
+    new CSVFieldSeparator($pluginlist, $inputargs, $hashArgOptLists);
     my $self = new SplitTextFile($pluginlist, $inputargs, $hashArgOptLists);
 
@@ -110,27 +114,26 @@
     $$textref =~ s/^(.*?)\r?\n//;
     my @csv_file_fields = ();
-    my $csv_file_field_line = $1 . ",";  # To make the regular expressions simpler
-    while ($csv_file_field_line ne "") {
-	# Handle quoted values
-	if ($csv_file_field_line =~ s/^\"(.*?)\"\,//) {
-	    my $csv_file_field = $1;
-	    $csv_file_field =~ s/ //g;  # Remove any spaces from the field names
-	    push(@csv_file_fields, $csv_file_field);
-	}
-	# Normal comma-separated case
-	elsif ($csv_file_field_line =~ s/^(.*?)\,//) {
-	    my $csv_file_field = $1;
-	    $csv_file_field =~ s/ //g;  # Remove any spaces from the field names
-	    push(@csv_file_fields, $csv_file_field);
-	}
-	# The line must be formatted incorrectly
-	else {
-	    print STDERR "Error: Badly formatted CSV field line: $csv_file_field_line.\n";
-	    last;
-	}
+    my $csv_file_field_line = $1;
+
+    my $separate_char = $self->{'csv_field_separator'};
+    if ($separate_char =~ m/^auto$/i) {
+	$separate_char = $self->resolve_auto($csv_file_field_line,$self->{'plugin_type'});
+	# Replace the 'auto' setting the resolved value (for use later on)
+	$self->{'separate_char'} = $separate_char;
     }
 
-    $self->{'csv_file_fields'}->{$filename} = \@csv_file_fields;
-    ###print STDERR "**** CSV file fields joined ($filename) = ", join(" ||| ", @{$self->{'csv_file_fields'}->{$filename}}), "\n";
+    my $csv = Text::CSV->new();
+    $csv->sep_char($separate_char);
+ 
+    if ($csv->parse($csv_file_field_line)) {
+	@csv_file_fields = $csv->fields;
+    }
+    else {
+	print STDERR "Error: Badly formatted CSV field line: $csv_file_field_line.\n";
+    }
+
+    $self->{'csv_file_fields'} = \@csv_file_fields;
+	
+    # print STDERR "**** CSV file fields joined = ", join(" ||| ", @{$self->{'csv_file_fields'}}), "\n";
 }
 
@@ -144,38 +147,42 @@
     my $section = $doc_obj->get_top_section();
     my $csv_line = $$textref;
-
-    my $filename_full_path = &FileUtils::filenameConcatenate($base_dir,$file);
-    my @csv_file_fields = @{$self->{'csv_file_fields'}->{$filename_full_path}};
-
-    ###print STDERR "**** CSV file fields joined = ", join(" ||| ", @csv_file_fields), "\n";
-
-     # Add the raw line as the document text
+    my @csv_file_fields = @{$self->{'csv_file_fields'}};	
+	
+    # Add the raw line as the document text
     $doc_obj->add_utf8_text($section, $csv_line);
 
+    my $separate_char = $self->{'separate_char'};
+
+    my $md_val_sep = $self->{'metadata_value_separator'};
+    undef $md_val_sep if ($md_val_sep eq "");
+
+    my $csv = Text::CSV->new();
+    $csv->sep_char($separate_char);
+ 
     # Build a hash of metadata name to metadata value for this line
-    my $i = 0;
-    $csv_line .= ",";  # To make the regular expressions simpler
-    while ($csv_line ne "") {
-	# Metadata values containing commas are quoted
-	if ($csv_line =~ s/^\"(.*?)\"\,//) {
+    if ($csv->parse($csv_line)) {
+	my @md_vals = $csv->fields;
+	my $md_vals_len = scalar(@md_vals);
+
+	for (my $i=0; $i<$md_vals_len; $i++) {
+	    my $md_val = $md_vals[$i];
 	    # Only bother with non-empty values
-	    if ($1 ne "" && defined($csv_file_fields[$i])) {
-		$doc_obj->add_utf8_metadata($section, $csv_file_fields[$i], $1);
+	    if ($md_val ne "" && defined($csv_file_fields[$i])) {
+		if (defined $md_val_sep) {
+		    my $md_name = $csv_file_fields[$i];
+
+		    my @within_md_vals = split(/${md_val_sep}/,$md_val);
+		    foreach my $within_md_val (@within_md_vals) {
+			$doc_obj->add_utf8_metadata($section, $md_name, $within_md_val);
+		    }
+		}
+		else {
+		    $doc_obj->add_utf8_metadata($section, $csv_file_fields[$i], $md_val);
+		}
 	    }
 	}
-	# Normal comma-separated case
-	elsif ($csv_line =~ s/^(.*?)\,//) {
-	    # Only bother with non-empty values
-	    if ($1 ne "" && defined($csv_file_fields[$i])) {
-		$doc_obj->add_utf8_metadata($section, $csv_file_fields[$i], $1);
-	    }
-	}
-	# The line must be formatted incorrectly
-	else {
-	    print STDERR "Error: Badly formatted CSV line: $csv_line.\n";
-	    last;
-	}
-
-	$i++;
+    }
+    else {
+	print STDERR "Error: Badly formatted CSV line: $csv_line.\n";
     }
 
Index: /main/trunk/greenstone2/perllib/plugins/MetadataCSVPlugin.pm
===================================================================
--- /main/trunk/greenstone2/perllib/plugins/MetadataCSVPlugin.pm	(revision 34248)
+++ /main/trunk/greenstone2/perllib/plugins/MetadataCSVPlugin.pm	(revision 34249)
@@ -30,4 +30,5 @@
 use BaseImporter;
 use MetadataRead;
+use CSVFieldSeparator;
 
 use strict;
@@ -39,9 +40,11 @@
 
 use Encode;
+use Text::CSV;
 
 # methods with identical signatures take precedence in the order given in the ISA list.
 sub BEGIN {
-    @MetadataCSVPlugin::ISA = ('MetadataRead', 'BaseImporter');
-}
+    @MetadataCSVPlugin::ISA = ('MetadataRead', 'BaseImporter', 'CSVFieldSeparator');
+}
+
 
 
@@ -72,4 +75,5 @@
     push(@{$hashArgOptLists->{"OptList"}},$options);
 
+    new CSVFieldSeparator($pluginlist, $inputargs, $hashArgOptLists);
     my $self = new BaseImporter($pluginlist, $inputargs, $hashArgOptLists);
 
@@ -108,9 +112,8 @@
 	$processor, $gli, $aux) = @_;
 
-    # Read metadata from CSV files
-    my $filename = &util::filename_cat($base_dir, $file);
-    if ($filename !~ /\.csv$/ || !-f $filename) {
-	return undef;
-    }
+    # can we process this file??
+    my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
+    return undef unless $self->can_process_this_file_for_metadata($filename_full_path);
+    
     print STDERR "\n<Processing n='$file' p='MetadataCSVPlugin'>\n" if ($gli);
     print STDERR "MetadataCSVPlugin: processing $file\n" if ($self->{'verbosity'}) > 1;
@@ -120,10 +123,10 @@
 
     # add the file to the block list so that it won't be processed in read, as we will do all we can with it here
-    $self->block_raw_filename($block_hash,$filename);
+    $self->block_raw_filename($block_hash,$filename_full_path);
 
 
     # Read the CSV file to get the metadata
     my $csv_file_content;
-    open(CSV_FILE, "$filename");
+    open(CSV_FILE, "$filename_full_path");
     my $csv_file_reader = new multiread();
     $csv_file_reader->set_handle('MetadataCSVPlugin::CSV_FILE');
@@ -140,7 +143,29 @@
     $csv_file_content =~ s/\r/\n/g;  # Handle non-Unix line endings
     $csv_file_content =~ s/\n+/\n/g;
+
+    my $separate_char = $self->{'csv_field_separator'};
+
+    my $md_val_sep = $self->{'metadata_value_separator'};
+    undef $md_val_sep if ($md_val_sep eq "");
+
     my @csv_file_lines = split(/\n/, $csv_file_content);
     my $csv_file_field_line = shift(@csv_file_lines);
-    my @csv_file_fields = split(/\,/, $csv_file_field_line);
+
+    if ($separate_char =~ m/^auto$/i) {
+	$separate_char = $self->resolve_auto($csv_file_field_line,$self->{'plugin_type'});
+    }
+
+    my $csv = Text::CSV->new();
+    $csv->sep_char($separate_char);
+ 
+    my @csv_file_fields = undef;
+    if ($csv->parse($csv_file_field_line)) {
+	@csv_file_fields = $csv->fields;
+    }
+    else {
+	$self->print_error($outhandle, $failhandle, $gli, $filename_full_path, "Error: Badly formatted CSV header line: $csv_file_field_line");
+	return -1;
+    }
+
     my $found_filename_field = 0;
     for (my $i = 0; $i < scalar(@csv_file_fields); $i++) {
@@ -156,5 +181,5 @@
 
     if (!$found_filename_field) {
-	$self->print_error($outhandle, $failhandle, $gli, $filename, "No Filename field in CSV file");
+	$self->print_error($outhandle, $failhandle, $gli, $filename_full_path, "No Filename field in CSV file");
 	return -1; # error
     }
@@ -164,41 +189,57 @@
 	next if ($csv_line =~ /^\s*$/);
 	my $orig_csv_line = $csv_line;
+
 	# Build a hash of metadata name to metadata value for this line
 	my %csv_line_metadata;
-	my $i = 0;
-	$csv_line .= ",";  # To make the regular expressions simpler
-	while ($csv_line ne "") {
-	    # Metadata values containing commas are quoted
-	    if ($csv_line =~ s/^\"(.*?)\"\,//) {
+
+	if ($csv->parse($csv_line)) {
+	    my @md_vals = $csv->fields;
+	    my $md_vals_len = scalar(@md_vals);
+	    
+	    for (my $i=0; $i<$md_vals_len; $i++) {
+		my $md_val = $md_vals[$i];
 		# Only bother with non-empty values
-		if ($1 ne "" && defined($csv_file_fields[$i])) {
-		    if (!defined $csv_line_metadata{$csv_file_fields[$i]}) {
-			$csv_line_metadata{$csv_file_fields[$i]} = [];
+		if ($md_val ne "" && defined($csv_file_fields[$i])) {
+
+		    my $md_name = $csv_file_fields[$i];
+
+		    if (!defined $md_name) {
+			$csv_line_metadata{$md_name} = [];
 		    }
-		    push (@{$csv_line_metadata{$csv_file_fields[$i]}}, $1);
+
+		    if (defined $md_val_sep) {			
+			
+			my @within_md_vals = split(/${md_val_sep}/,$md_val);
+			#push (@{$csv_line_metadata{$md_name}}, @within_md_vals);
+
+			# protect square brackets in metadata values by hex entity encoding them
+			# As unescaped square bracket chars in metadata
+			# have special meaning in GS' Java runtime code
+			my @escaped_within_md_vals = ();
+			for my $meta_value (@within_md_vals) {
+			    $meta_value =~ s/\[/&\#091;/g;
+			    $meta_value =~ s/\]/&\#093;/g;
+			    push(@escaped_within_md_vals, $meta_value);
+			}
+			push (@{$csv_line_metadata{$md_name}}, @escaped_within_md_vals);
+
+#			foreach my $within_md_val (@within_md_vals) {
+#			    push (@{$csv_line_metadata{$md_name}}, $within_md_val);
+#			}
+		    }
+		    else {
+			#push (@{$csv_line_metadata{$md_name}}, $md_val);
+			# protect square brackets in metadata values by hex entity encoding them
+			my $escaped_metadata_value = $md_val;
+			$escaped_metadata_value =~ s/\[/&\#091;/g;
+			$escaped_metadata_value =~ s/\]/&\#093;/g;
+			push (@{$csv_line_metadata{$md_name}}, $escaped_metadata_value);
+		    }
 		}
 	    }
-	    # Normal comma-separated case
-	    elsif ($csv_line =~ s/^(.*?)\,//) {
-		# Only bother with non-empty values
-		if ($1 ne "" && defined($csv_file_fields[$i])) {
-		    if (!defined $csv_line_metadata{$csv_file_fields[$i]}) {
-			$csv_line_metadata{$csv_file_fields[$i]} = [];
-		    }
-		    # remove any surrounding quotes. (When exporting to CSV, some spreadsheet
-		    # programs add quotes even around field values that don't contain commas.)
-		    my $value = $1;
-		    $value =~ s/^"//;
-		    $value =~ s/"$//;
-		    push (@{$csv_line_metadata{$csv_file_fields[$i]}}, $value);
-		}
-	    }
-	    # The line must be formatted incorrectly
-	    else {
-		$self->print_error($outhandle, $failhandle, $gli, $filename, "Badly formatted CSV line: $csv_line");
-		last;
-	    }
-
-	    $i++;
+	}
+	else {
+	    $self->print_error($outhandle, $failhandle, $gli, $filename_full_path, "Badly formatted CSV line: $csv_line");
+	    last;
 	}
 
@@ -206,5 +247,5 @@
 	my $csv_line_filename_array = $csv_line_metadata{"Filename"};
 	if (!defined $csv_line_filename_array) {
-	    $self->print_error($outhandle, $failhandle, $gli, $filename, "No Filename metadata in CSV line: $orig_csv_line");
+	    $self->print_error($outhandle, $failhandle, $gli, $filename_full_path, "No Filename metadata in CSV line: $orig_csv_line");
 	    next;
 	}
@@ -255,5 +296,5 @@
 	}
 	# maps the file to full path
-	&extrametautil::setmetafile_for_named_file($extrametafile, $csv_line_filename, $file, $filename);
+	&extrametautil::setmetafile_for_named_file($extrametafile, $csv_line_filename, $file, $filename_full_path);
     }
 }
