+sub mpd_escape {
+ ($_) = @_;
+
+ # No way to encode literal newlines in the protocol, so we convert
+ # any newlines in the arguments into a space, which can help with
+ # shell quoting.
+ s/\n/ /g;
+
+ if (/[ \t\\"]/) {
+ s/[\\"]/\\$&/g;
+ return "\"$_\"";
+ }
+ return $_;
+}
+
+sub mpd_exec {
+ print $sock join(' ', @_), "\n";
+ while (<$sock>) {
+ last if (/^OK/);
+ print;
+ exit 1 if (/^ACK/);
+ }
+}
+
+if (@ARGV) {
+ mpd_exec(map { mpd_escape($_) } @ARGV)
+} else {
+ while (<>) {
+ chomp;
+ mpd_exec($_);
+ }