+# Given a work MBID, return a hash reference containing all tracks
+# linked to that work. The hash keys are filenames.
+sub get_tracks_by_work_mbid {
+ my %matches;
+ my $entry;
+
+ foreach my $mbid (@_) {
+ mpd_exec("search", "(MUSICBRAINZ_WORKID == \"$mbid\")");
+ while (<$sock>) {
+ last if (/^OK/);
+ die($_) if (/^ACK/);
+
+ if (/^(\w+): (.*)$/) {
+ if ($1 eq "file") {
+ if (exists($matches{$2})) {
+ $entry = $matches{$2};
+ } else {
+ $entry = {};
+ $matches{$2} = $entry;
+ }
+ }
+
+ add_track_metadata($entry, $1, $2);
+ }
+ }
+ }
+
+ return \%matches;
+}
+
+# Given a track MBID, return a hash reference containing all "related"
+# tracks in the MPD database. The hash keys are filenames.
+#
+# Currently tracks are considered "related" if their associated recordings
+# have at least one work in common.
+sub get_tracks_by_track_mbid {
+ my ($mbid) = @_;
+ my %source;
+ my %matches;
+ my $entry;
+
+ return \%matches unless ($mbid);
+ mpd_exec("search", "(MUSICBRAINZ_RELEASETRACKID == \"$mbid\")");
+ while (<$sock>) {
+ last if (/^OK/);
+ die($_) if (/^ACK/);
+
+ if (/^(\w+): (.*)$/) {
+ add_track_metadata(\%source, $1, $2);
+ }
+ }
+
+ # Always include the current track
+ $matches{$source{file}} = \%source;
+
+ # Find all tracks related by work
+ foreach my $mbid (get_track_metadata(\%source, "MUSICBRAINZ_WORKID")) {
+ my $related = get_tracks_by_work_mbid($mbid);
+ foreach (keys %$related) {
+ $matches{$_} //= $related->{$_};
+ }
+ }
+
+ return \%matches;
+}
+