def ms_to_timecode(ms, fps=None):
    """
    Formats milliseconds into an hour-minute-second timecode,
    like 01:30:43 if `fps` is not set, or a hour-minute-second-frame
    timecode if fps is set, like 01:30:43:12

    When fps is set to 29.97 (NTSC), it autocorrects it to 30000/1001
    (29.97002997002997).
    """
    hours = ms // 3600000
    ms = ms - hours * 3600000
    minutes = ms // 60000
    ms = ms - minutes * 60000
    seconds = ms // 1000
    ms = ms - seconds * 1000
    if fps:
        if fps == 29.97:
            fps = 30000 / 1001.0
        frame = ms / (1000.0 / fps)
        tc = '%02d:%02d:%02d:%02d' % (hours, minutes, seconds, frame)
    else:
        tc = '%02d:%02d:%02d' % (hours, minutes, seconds)
    return tc
