"""Convert Nintendo DS SSEQ songs (via 2SF rips) to Impulse Tracker modules."""
import sys, os, struct, math, re
import numpy as np
sys.path.insert(0, os.path.dirname(__file__))
from sdat import SDAT, load_psf
import seq

MIXVOL = int(os.environ.get('MIXVOL', 120))
UPDATE_HZ = 33513982 / (64 * 2728)  # ~191.97 Hz sequencer/envelope update rate

SUST = [-32768, -722, -721, -651, -601, -562, -530, -503, -480, -460, -442, -425, -410, -396, -383, -371,
        -360, -349, -339, -330, -321, -313, -305, -297, -289, -282, -276, -269, -263, -257, -251, -245,
        -239, -234, -229, -224, -219, -214, -210, -205, -201, -196, -192, -188, -184, -180, -176, -173,
        -169, -165, -162, -158, -155, -152, -149, -145, -142, -139, -136, -133, -130, -127, -125, -122,
        -119, -116, -114, -111, -109, -106, -103, -101, -99, -96, -94, -91, -89, -87, -85, -82,
        -80, -78, -76, -74, -72, -70, -68, -66, -64, -62, -60, -58, -56, -54, -52, -50,
        -49, -47, -45, -43, -42, -40, -38, -36, -35, -33, -31, -30, -28, -27, -25, -23,
        -22, -20, -19, -17, -16, -14, -13, -11, -10, -8, -7, -6, -4, -3, -1, 0]
SCALE = [-32768, -421, -361, -325, -300, -281, -265, -252, -240, -230, -221, -212, -205, -198, -192, -186,
         -180, -175, -170, -165, -161, -156, -152, -148, -145, -141, -138, -134, -131, -128, -125, -122,
         -120, -117, -114, -112, -110, -107, -105, -103, -100, -98, -96, -94, -92, -90, -88, -86,
         -85, -83, -81, -79, -78, -76, -74, -73, -71, -70, -68, -67, -65, -64, -62, -61,
         -60, -58, -57, -56, -54, -53, -52, -51, -49, -48, -47, -46, -45, -43, -42, -41,
         -40, -39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25,
         -24, -23, -23, -22, -21, -20, -19, -18, -17, -17, -16, -15, -14, -13, -12, -12,
         -11, -10, -9, -9, -8, -7, -6, -6, -5, -4, -3, -3, -2, -1, -1, 0]
ATK_LUT = [0x00, 0x01, 0x05, 0x0E, 0x1A, 0x26, 0x33, 0x3F, 0x49, 0x54, 0x5C, 0x64, 0x6D, 0x74, 0x7B, 0x7F, 0x84, 0x89, 0x8F]


def cb_to_lin(cb):
    return 0.0 if cb <= -723 else 10 ** (cb / 200.0)


def cnv_attack(a):
    if a & 0x80: a = 0
    return ATK_LUT[0x7F - a] if a >= 0x6D else 0xFF - a


def cnv_fall(f):
    if f & 0x80: f = 0
    if f == 0x7F: return 0xFFFF
    if f == 0x7E: return 0x3C00
    if f < 0x32: return (f << 1) + 1
    return 0x1E00 // (0x7E - f)


def cdiv(a, b):  # C-style truncating division
    q = abs(a) // abs(b)
    return q if (a >= 0) == (b >= 0) else -q


def simplify(points, tol):
    """Ramer-Douglas-Peucker on (x, y) points."""
    if len(points) <= 2: return points
    (x0, y0), (x1, y1) = points[0], points[-1]
    best, bi = -1, 0
    for i in range(1, len(points) - 1):
        x, y = points[i]
        yl = y0 + (y1 - y0) * ((x - x0) / (x1 - x0) if x1 != x0 else 0)
        d = abs(y - yl)
        if d > best: best, bi = d, i
    if best <= tol: return [points[0], points[-1]]
    return simplify(points[:bi + 1], tol)[:-1] + simplify(points[bi:], tol)


def make_envelope(a, d, s, r, ticks_per_update):
    """Simulate the DS ADSR and return IT envelope points [(tick, 0..64)], sustain index."""
    atk, dec, sus, rel = cnv_attack(a), cnv_fall(d), SUST[s if s < 128 else 127], cnv_fall(r)
    ampl = -723 * 128
    curve = []  # per update linear values (attack+decay)
    n = 0
    state = 'A'
    while n < 20000:
        if state == 'A':
            old = ampl >> 7
            new = ampl
            while True:
                new = cdiv(new * atk, 256)
                if (new >> 7) != old: break
            ampl = new
            if ampl == 0: state = 'D'
        elif state == 'D':
            ampl -= dec
            if ampl <= sus * 128:
                ampl = sus * 128; state = 'S'
        curve.append((n, cb_to_lin(ampl >> 7)))
        n += 1
        if state == 'S': break
    # attack/decay part in IT ticks
    ad = [(t * ticks_per_update, v * 64) for t, v in curve]
    ad = [(0.0, ad[0][1])] + ad if ad[0][0] != 0 else ad
    pts = simplify(ad, 1.0)
    pts = [(int(round(t)), int(round(v))) for t, v in pts]
    # release: linear in cB from sustain level down to silence
    rel_pts = []
    level = sus * 128
    if rel >= 0xFFFF:
        rel_pts.append((1, 0))
    else:
        total_updates = (level + 723 * 128) / rel
        for db_drop in (0, 30, 60, 100, 150, 200, 260, 330, 400):  # cB below sustain
            target = level - db_drop * 128
            u = min(total_updates, db_drop * 128 / rel)
            rel_pts.append((u * ticks_per_update, cb_to_lin(max(target, -723 * 128) >> 7) * 64))
            if cb_to_lin(target >> 7) * 64 < 0.5: break
        rel_pts.append((total_updates * ticks_per_update, 0))
        rel_pts = [(int(round(t)), int(round(v))) for t, v in rel_pts]
    # merge, enforce increasing ticks, max 25 points, tick cap
    out = []
    for t, v in pts:
        if out and t <= out[-1][0]: t = out[-1][0] + 1
        out.append((t, max(0, min(64, v))))
    sus_idx = len(out) - 1
    base = out[-1][0]
    for t, v in rel_pts[1:]:
        t = base + max(1, t)
        if t <= out[-1][0]: t = out[-1][0] + 1
        if t > 9999: t = 9999
        if t <= out[-1][0]: break
        out.append((t, max(0, min(64, v))))
    if len(out) > 25:
        keep = out[:sus_idx + 1]
        rest = out[sus_idx + 1:]
        if len(keep) > 18:
            step = (len(keep) - 1) / 17.0
            keep = [keep[int(round(i * step))] for i in range(18)]
            sus_idx = len(keep) - 1
        out = keep + rest[:25 - len(keep)]
    if out[-1][1] != 0 and len(out) < 25:
        out.append((min(9999, out[-1][0] + 1), 0)) if out[-1][0] < 9999 else None
    return out, sus_idx


class Module:
    def __init__(self):
        self.samples = []   # dict(name, pcm int16, rate, loop, ls, le, pan)
        self.instruments = []
        self.patterns = []  # list of (rows, {(row,ch): cell})
        self.orders = []


def psg_square(duty):
    steps = [-0x7FFF] * 8
    pos = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 0}[duty]
    for i in range(8 - pos, 8): steps[i] = 0x7FFF
    pcm = np.repeat(np.array(steps, dtype=np.int32), 8)
    return pcm.astype(np.int16), 262 * 64  # DS PSG square: 8 steps at 262*8 Hz for the region's base key


def build(sd, sid, name, tags):
    info = sd.seqinfo[sid]
    bank = sd.sbnk(info['bank'])
    wa_idx = sd.bankinfo[info['bank']]['wa']
    tracks, tempos, total = seq.run(sd.sseq(sid))
    tempo_vals = [v for _, v in tempos] or [120]
    k = 2
    while max(tempo_vals) * 2 / k > 255: k += 1
    while 12 % k: k += 1
    speed = 12 // k
    tick_of = lambda t: int(round(t / k))
    first_tempo = tempo_vals[0]
    it_tempo = lambda tm: max(32, min(255, int(round(tm * 2 / k))))
    ticks_per_update = (0.8 * first_tempo / k) / UPDATE_HZ

    mod = Module()
    samp_map, inst_map = {}, {}

    def get_sample(reg):
        key = (reg['type'], reg['swar'], reg['swav'], reg['pan'])
        if key in samp_map: return samp_map[key]
        if reg['type'] == 1:
            w = sd.swar(wa_idx[reg['swar']])[reg['swav']]
            swar_name = sd.wanames.get(wa_idx[reg['swar']], 'WAR%d' % wa_idx[reg['swar']])
            s = dict(name=('%s #%d' % (swar_name, reg['swav']))[:25], pcm=w['pcm'], rate=w['rate'],
                     loop=w['loop'], ls=w['loopstart'], le=w['length'])
        elif reg['type'] == 2:
            pcm, rate = psg_square(reg['swav'] & 7)
            s = dict(name='PSG square duty %d' % (reg['swav'] & 7), pcm=pcm, rate=rate, loop=True, ls=0, le=len(pcm))
        else:
            rng = 0x7FFF; out = []
            for _ in range(32767 * 2):
                if rng & 1: rng = (rng >> 1) ^ 0x6000; out.append(-0x3FFF)
                else: rng >>= 1; out.append(0x3FFF)
            pcm = np.array(out, dtype=np.int16)
            s = dict(name='PSG noise', pcm=pcm, rate=262 * 8, loop=True, ls=0, le=len(pcm))
        s['pan'] = None if reg['pan'] == 64 else reg['pan']
        mod.samples.append(s)
        samp_map[key] = len(mod.samples)
        return samp_map[key]

    def find_region(patch, key):
        if patch >= len(bank): return None
        for r in bank[patch]['regions']:
            if r['lo'] <= key <= r['hi'] and r['type'] in (1, 2, 3): return r
        return None

    def get_inst(patch, reg):
        adsr = (reg['a'], reg['d'], reg['s'], reg['r'])
        key = (patch, adsr)
        if key in inst_map: return inst_map[key]
        keymap = []
        for note in range(120):
            r = find_region(patch, note)
            if r is None or (r['a'], r['d'], r['s'], r['r']) != adsr:
                keymap.append((note, 0)); continue
            sn = get_sample(r)
            out = note - r['note'] + 60
            if r['type'] != 1: out = note - r['note'] + 60
            keymap.append((max(0, min(119, out)), sn))
        env, sus = make_envelope(*adsr, ticks_per_update)
        bname = sd.banknames.get(info['bank'], 'BANK%d' % info['bank'])
        nreg = sum(1 for _ in bank[patch]['regions'])
        kind = {16: 'drums', 17: 'split'}.get(bank[patch]['rec'], '')
        nm = 'P%03d %s' % (patch, kind)
        if sum(1 for kk in inst_map if kk[0] == patch) or any(
                (r['a'], r['d'], r['s'], r['r']) != adsr for r in bank[patch]['regions']):
            nm += ' ADSR %d/%d/%d/%d' % adsr
        # note-offs only matter if the release is audible: looped samples or a release under ~3 s
        rel_secs = (723 * 128 / cnv_fall(adsr[3])) / UPDATE_HZ
        looped = any(mod.samples[sn - 1]['loop'] for _, sn in keymap if sn)
        mod.instruments.append(dict(name=nm.strip()[:25], keymap=keymap, env=env, sus=sus,
                                    noff=looped or rel_secs < 3.0))
        inst_map[key] = len(mod.instruments)
        return inst_map[key]

    # ---- per track: notes and control curves ----
    chans = []      # list of dict(track, notes=[...])
    track_chans = {}
    only = os.environ.get('ONLY')
    for tr in tracks:
        if only is not None and tr.tid != int(only): continue
        notes = []
        for e in tr.events:
            if e['ev'] != 'note': continue
            reg = find_region(e['patch'], e['key'])
            if reg is None: continue
            notes.append(dict(t=e['t'], end=e['t'] + e['dur'], key=e['key'], vel=e['vel'],
                              inst=get_inst(e['patch'], reg)))
        if not notes:
            continue
        # interval partitioning by IT tick (note-off frees the channel)
        subs = []
        for n in sorted(notes, key=lambda n: (n['t'], n['key'])):
            st, en = tick_of(n['t']), max(tick_of(n['end']), tick_of(n['t']) + 1)
            n['st'], n['en'] = st, en
            for s in subs:
                if s['free'] <= st:
                    s['notes'].append(n); s['free'] = en; break
            else:
                subs.append(dict(notes=[n], free=en))
        if not subs: subs = [dict(notes=[], free=0)]
        track_chans[tr.tid] = []
        for s in subs:
            track_chans[tr.tid].append(len(chans))
            chans.append(dict(track=tr, notes=s['notes']))
    nch = len(chans) + 1
    if nch > 64:
        raise RuntimeError('too many channels: %d' % nch)
    ctl = len(chans)

    total_ticks = tick_of(total)
    nrows = total_ticks // speed + 1
    nrows = ((nrows + 15) // 16) * 16
    cells = {}

    def cell(r, c):
        return cells.setdefault((r, c), {})

    def put_eff(r, c, cmd, prm, defer=False, maxdefer=0):
        for rr in range(r, r + 1 + maxdefer):
            if rr >= nrows: return False
            ce = cell(rr, c)
            if 'eff' not in ce:
                ce['eff'] = (cmd, prm); return True
        return False

    # tempo changes on control channel
    for t, tm in tempos:
        q = tick_of(t); r = q // speed
        put_eff(r, ctl, 20, it_tempo(tm), maxdefer=4)

    VOLUME_FLOOR = 0
    for ci, ch in enumerate(chans):
        tr = ch['track']
        # 1. notes and note-offs
        busy = {}
        for i, n in enumerate(ch['notes']):
            r, dly = divmod(n['st'], speed)
            ce = cell(r, ci)
            if 'note' in ce:
                continue
            ce['note'] = n['key'] if n['key'] < 120 else 119
            ce['ins'] = n['inst']
            ce['vol'] = max(1, int(round(64 * cb_to_lin(SUST[n['vel'] & 0x7F])))) if n['vel'] else 0
            if dly: ce['eff'] = (19, 0xD0 | dly)
            nxt = ch['notes'][i + 1]['st'] if i + 1 < len(ch['notes']) else None
            if (nxt is None or nxt > n['en']) and mod.instruments[n['inst'] - 1]['noff']:
                r2, d2 = divmod(n['en'], speed)
                if r2 < nrows:
                    c2 = cell(r2, ci)
                    if 'note' not in c2:
                        c2['note'] = 255
                        if d2 and 'eff' not in c2: c2['eff'] = (19, 0xD0 | d2)
        # sounding intervals (in rows) for per-row controls
        sounding = np.zeros(nrows + 1, dtype=bool)
        for n in ch['notes']:
            sounding[n['st'] // speed: n['en'] // speed + 1] = True

        # 2. control curves: volume, pan, bend, moddepth -> per row values (last value in row wins)
        def curve(evname, default):
            vals = {}
            for e in tr.events:
                if e['ev'] == evname:
                    vals[tick_of(e['t']) // speed] = e['v']
            return vals
        volc, panc, bendc, modc = curve('vol', 127), curve('pan', 64), curve('bend', 0), curve('moddepth', 0)
        exprc, brc, mspc, mrc = curve('expr', 127), curve('bendrange', 2), curve('modspeed', 16), curve('modrange', 1)
        bendrange, modrange, pend_expr = 2, 1, 127
        # Notes per row for bend reset
        note_rows = {}
        for n in ch['notes']:
            note_rows.setdefault(n['st'] // speed, n)

        cur_vol, cur_pan = None, None
        pend_vol, pend_pan = 127, 64
        bend, applied = 0, 0
        depth = 0
        modspeed = 16
        for r in range(nrows):
            if r in volc: pend_vol = volc[r]
            if r in panc: pend_pan = panc[r]
            if r in bendc: bend = bendc[r]
            if r in modc: depth = modc[r]
            if r in exprc: pend_expr = exprc[r]
            if r in brc: bendrange = brc[r]
            if r in mspc: modspeed = mspc[r]
            if r in mrc: modrange = mrc[r]
            ce = cell(r, ci) if (r, ci) in cells else None
            # bend handling
            target = (bend * bendrange) >> 1 if bend >= 0 else -((-bend * bendrange) >> 1)  # 1/64 semitone
            if ce is not None and isinstance(ce.get('note'), int) and ce['note'] < 120:
                applied = 0
            delta = target - applied
            if delta and sounding[r]:
                ce = cell(r, ci)
                if 'eff' not in ce:
                    ad = abs(delta)
                    if ad <= 15:
                        ce['eff'] = (6 if delta > 0 else 5, 0xE0 | ad); applied += delta
                    else:
                        x = min(15, int(round(ad / 4)))
                        ce['eff'] = (6 if delta > 0 else 5, 0xF0 | x); applied += (x * 4 if delta > 0 else -x * 4)
            # channel volume
            if (pend_vol, pend_expr) != cur_vol:
                m = int(round(64 * cb_to_lin(SUST[pend_vol & 0x7F] + SUST[pend_expr & 0x7F])))
                if put_eff(r, ci, 13, m): cur_vol = (pend_vol, pend_expr)
            if pend_pan != cur_pan:
                if put_eff(r, ci, 24, max(0, min(255, pend_pan * 2))): cur_pan = pend_pan
            # vibrato
            if depth and sounding[r]:
                tm = first_tempo
                y = min(15, int(round(depth * modrange * 127 / 1024)))
                x = max(1, min(15, int(round(30 * modspeed * k / tm))))
                if y:
                    ce = cell(r, ci)
                    if 'eff' not in ce:
                        ce['eff'] = (8, (x << 4) | y)
                    elif 'vol' not in ce and 'note' not in ce:
                        ce['vol'] = 203 + min(9, y)
    # control channel: song length end marker not needed (song restarts)

    # split into patterns of 64 rows
    prow = 64
    np_ = (nrows + prow - 1) // prow
    for p in range(np_):
        rows = min(prow, nrows - p * prow)
        pdata = {}
        for (r, c), ce in cells.items():
            if p * prow <= r < p * prow + rows and ce:
                pdata[(r - p * prow, c)] = ce
        mod.patterns.append((max(rows, 1), pdata))
        mod.orders.append(p)
    mod.nch = nch
    mod.speed = speed
    mod.tempo = it_tempo(first_tempo)
    mod.gv = int(round(128 * cb_to_lin(SCALE[info['vol']])))
    mod.title = name[:25]
    mod.message = ('%s\r%s\rComposer: %s\r%s\rConverted from Nintendo DS SSEQ #%d (%s)' % (
        tags.get('game', ''), tags.get('title', name), tags.get('artist', ''), tags.get('copyright', ''), sid,
        sd.seqnames.get(sid, '')))
    mod.chan_names = []
    import collections
    for tid, cl in track_chans.items():
        pc = collections.Counter(e['patch'] for e in tracks[tid].events if e['ev'] == 'note').most_common(1)
        for j, ci in enumerate(cl):
            sfx = chr(97 + j) if len(cl) > 1 else ''
            mod.chan_names.append('T%02d%s P%03d' % (tid, sfx, pc[0][0] if pc else 0))
    mod.chan_names.append('Tempo')
    return mod


def write_it(mod, fn, mixvol=MIXVOL):
    def pstr(s, n):
        return s.encode('latin-1', 'replace')[:n].ljust(n, b'\0')
    ordn = len(mod.orders) + 1
    orders = bytes(mod.orders) + b'\xff'
    insn, smpn, patn = len(mod.instruments), len(mod.samples), len(mod.patterns)
    msg = mod.message.encode('latin-1', 'replace') + b'\0'
    hdr = bytearray()
    hdr += b'IMPM' + pstr(mod.title, 26) + bytes([4, 16])
    hdr += struct.pack('<HHHHHHHH', ordn, insn, smpn, patn, 0x5131, 0x0214, 1 | 4 | 8, 1)  # special: message
    hdr += struct.pack('<BBBBBBH', 128 if mod.gv > 128 else mod.gv, mixvol, mod.speed, mod.tempo, 128, 0, len(msg))
    msgoff_pos = len(hdr); hdr += b'\0\0\0\0' + b'\0\0\0\0'
    pan = [32] * mod.nch + [32 | 128] * (64 - mod.nch)
    hdr += bytes(pan) + bytes([64] * 64)
    hdr += orders
    ptr_pos = len(hdr)
    hdr += b'\0' * (4 * (insn + smpn + patn))
    out = bytearray(hdr)

    def setptr(i, v): struct.pack_into('<I', out, ptr_pos + 4 * i, v)
    # channel names (OpenMPT extension "CNAM", read directly after the pointer tables)
    cn = b''.join(pstr(n, 20) for n in mod.chan_names)
    out += b'CNAM' + struct.pack('<I', len(cn)) + cn
    struct.pack_into('<I', out, msgoff_pos, len(out)); out += msg
    # instruments
    for i, ins in enumerate(mod.instruments):
        setptr(i, len(out))
        b = bytearray(b'IMPI' + b'\0' * 12 + b'\0')
        b += bytes([2, 0, 0])            # NNA=note off, DCT off, DCA cut
        b += struct.pack('<HbBBBBB', 0, 0, 60, 128, 32 | 128, 0, 0)
        b += struct.pack('<HBB', 0x0214, sum(1 for _ in {s for _, s in ins['keymap'] if s}), 0)
        b += pstr(ins['name'], 26)
        b += bytes([0, 0, 0, 0]) + struct.pack('<H', 0xFFFF)
        for note, smp in ins['keymap']: b += bytes([note, smp])
        env = ins['env']
        e = bytearray([1 | 4, len(env), 0, 0, ins['sus'], ins['sus']])
        for t, v in env: e += struct.pack('<BH', v, t)
        e += b'\0' * (75 - 3 * len(env)) + b'\0'
        b += e
        for _ in range(2): b += bytes([0, 2, 0, 0, 0, 0]) + struct.pack('<bH', 0, 0) + struct.pack('<bH', 0, 100) + b'\0' * 69 + b'\0'
        b += b'\0' * 4
        assert len(b) == 554, len(b)
        out += b
    # sample headers
    smp_hdr_pos = []
    for i, s in enumerate(mod.samples):
        setptr(insn + i, len(out)); smp_hdr_pos.append(len(out))
        flags = 1 | 2 | (16 if s['loop'] else 0)
        b = bytearray(b'IMPS' + b'\0' * 12 + b'\0')
        b += bytes([64, flags, 64]) + pstr(s['name'], 26)
        b += bytes([1, (s['pan'] // 2) | 128 if s['pan'] is not None else 32])
        ln = len(s['pcm'])
        ls = s['ls'] if s['loop'] else 0
        le = min(s['le'], ln) if s['loop'] else 0
        if s['loop'] and le - ls < 1:
            b[0x12] = flags & ~16; ls = le = 0
        b += struct.pack('<IIIIIII', ln, ls, le, int(round(s['rate'])), 0, 0, 0)
        b += bytes([0, 0, 0, 0])
        assert len(b) == 80
        out += b
    # patterns
    for i, (rows, pdata) in enumerate(mod.patterns):
        setptr(insn + smpn + i, len(out))
        pk = bytearray()
        for r in range(rows):
            for c in range(mod.nch):
                ce = pdata.get((r, c))
                if not ce: continue
                mask = 0; body = bytearray()
                if 'note' in ce: mask |= 1; body.append(ce['note'])
                if 'ins' in ce: mask |= 2; body.append(ce['ins'])
                if 'vol' in ce: mask |= 4; body.append(ce['vol'])
                if 'eff' in ce: mask |= 8; body += bytes(ce['eff'])
                if not mask: continue
                pk += bytes([(c + 1) | 0x80, mask]) + body
            pk.append(0)
        out += struct.pack('<HH4x', len(pk), rows) + pk
    # sample data
    for i, s in enumerate(mod.samples):
        struct.pack_into('<I', out, smp_hdr_pos[i] + 0x48, len(out))
        out += s['pcm'].astype('<i2').tobytes()
    # OpenMPT channel name extension appended at end is optional; skip for compatibility
    open(fn, 'wb').write(out)


if __name__ == '__main__':
    lib, outdir = sys.argv[1], sys.argv[2]
    files = sys.argv[3:]
    prog, _ = load_psf(lib)
    rom = prog[8:]
    sd = SDAT(rom[rom.find(b'SDAT'):])
    os.makedirs(outdir, exist_ok=True)
    for f in files:
        p, tags = load_psf(f)
        sid = p[-2] | p[-1] << 8
        base = os.path.splitext(os.path.basename(f))[0]
        m = build(sd, sid, re.sub(r'^[0-9A-F]{4} ', '', base), tags)
        write_it(m, os.path.join(outdir, base + '.it'))
        print('%-40s ch=%2d pat=%3d ins=%2d smp=%2d speed=%d tempo=%d' % (base, m.nch, len(m.patterns), len(m.instruments), len(m.samples), m.speed, m.tempo))
