Perl sub/gsub + some small bug fixes