##
##  C/C++ multiline string literal breaking utility
##

use IO;

#   read in C/C++ source
my $file = $ARGV[0];
my $io = new IO::File "<$file";
my $src = '';
$src .= $_ while <$io>;
$io->close;

#   process C/C++ source
my $done = ''; my $this = ''; my $todo = $src;
my $inside = 0;
while ($todo =~ m/([\\"i]|\r?\n)/s) {
    $done .= $`; $this = $&; $todo = $';
    my $char = $1;
    if ($char eq '\\') {
        #   escaped character
        $this .= substr($todo, 0, 1);
        $todo =  substr($todo, 1);
    }
    elsif ($char eq '"') {
        #   toggle "inside string" mode
        $inside = !($inside);
    }
    elsif ($char =~ m|^\r?\n$|s) {
        #   in "inside string" mode, break string
        if ($inside) {
            $this = "\\n\"" . $this . "\"";
        }
    }
    $done .= $this;
}
$src = $done;

#   write out C/C++ source
$io = new IO::File ">$file";
$io->print($src);
$io->close;

