CompanionFiles.java

package libsidplay.sidtune;

import java.util.Locale;

/** Naming rules shared by filesystem, server and browser MUS loaders. */
public final class CompanionFiles {
    private CompanionFiles() {
    }

    public static boolean isMus(String name) {
        String lower = name.toLowerCase(Locale.ROOT);
        return lower.endsWith(".mus") || lower.endsWith(".str");
    }

    public static boolean isSecondary(String name) {
        String lower = name.toLowerCase(Locale.ROOT);
        return lower.endsWith(".str") || lower.endsWith("_b.mus");
    }

    /** A .mus file ending in _b is still the primary half of a .mus/.str pair. */
    public static boolean isSecondary(String name, String companionName) {
        String lower = name.toLowerCase(Locale.ROOT);
        return lower.endsWith(".str") || lower.endsWith("_b.mus")
                && companionName.toLowerCase(Locale.ROOT).endsWith("_a.mus");
    }

    public static String findStereoCompanion(String name, String[] siblings) {
        String lower = name.replace('\\', '/').toLowerCase(Locale.ROOT);
        String expected;
        if (lower.endsWith("_a.mus")) expected = lower.substring(0, lower.length() - 6) + "_b.mus";
        else if (lower.endsWith("_b.mus")) expected = lower.substring(0, lower.length() - 6) + "_a.mus";
        else if (lower.endsWith(".mus")) expected = lower.substring(0, lower.length() - 4) + ".str";
        else if (lower.endsWith(".str")) expected = lower.substring(0, lower.length() - 4) + ".mus";
        else return null;
        String result = match(name, expected, siblings);
        if (result == null && (lower.endsWith("_a.mus") || lower.endsWith("_b.mus"))) {
            result = match(name, lower.substring(0, lower.length() - 4) + ".str", siblings);
        }
        return result;
    }

    private static String match(String name, String expected, String[] siblings) {
        String result = null;
        for (String sibling : siblings) {
            if (sibling.replace('\\', '/').equalsIgnoreCase(expected)) {
                if (result != null) throw new IllegalArgumentException("Ambiguous stereo companion: " + name);
                result = sibling;
            }
        }
        return result;
    }
}