#!/bin/sh
#\
exec tclsh "$0" "$@"

proc tmplsubst {template data} {
    array set arr $data

    set percent 0
    set bracket 0
    set result  ""
    set brkfail 0
    set brktext ""

    foreach char [split $template ""] {
        set out ""

        if {$percent} {
            # Previous character was %.
            if {[string first $char {%[]}] != -1} {
                # %-escaped character.
                set out $char
            } elseif {[info exists arr(%$char)]} {
                # Successful % substitution.
                set out $arr(%$char)
            } elseif {$bracket} {
                # Do not emit bracketed region.
                set brkfail 1
            } else {
                # Emit failed %-string directly.
                set out %$char
            }
            set percent 0
        } elseif {$char eq "%"} {
            # Process next character specially.
            set percent 1
        } elseif {$char eq "\[" && !$bracket} {
            # Beginning of bracketed region.
            set bracket 1
            set brkfail 0
        } elseif {$char eq "]" && $bracket} {
            # End of bracketed region.
            set bracket 0
            if {!$brkfail} {
                # Success--- emit entire bracketed region.
                set out $brktext
            }
            set brktext ""
        } else {
            # Ordinary text.
            set out $char
        }

        if {$bracket} {
            # Inside bracketed region.  Buffer until region end.
            append brktext $out
        } else {
            # Outside bracketed region.  Emit directly.
            append result  $out
        }
    }

    if {$bracket && !$brkfail} {
        # Unterminated successful bracketed region.  Emit.
        append result $brktext
    }

    set result [regsub {_{2,}} $result _]   ;# Kill redundant "_"
    set result [regsub {\._} $result .]     ;# Remove _ adjacent to "."
    set result [regsub {_\.} $result .]

    return $result
}

proc encode {tracks} {
    # Input filename template.
    set in_tmpl track%n.cdda.wav

    # Output filename template.
    # set out_tmpl {%a.%l.[%d.]%n.%t[_(%c)].%f}
    set out_tmpl {/music/%a/%l/%a.%l.[%d.]%n.%t[_(%c)].%f}
    # set out_tmpl {various.%l.[%d.]%n.%a.%t[_(%c)].%f}
    # set out_tmpl {/music/%a/%l/[%d.]%n. %t [(%c)].%f}
    # set out_tmpl {%a - %t[ (%c)]}

    # Characters replacement map.
    set charmap {/ _-_}
    foreach char {. " "} {
        lappend charmap $char _
    }

    # Possible subtitions.
    set substmap {
        %a artist       %l album        %d disc         %n track
        %t title        %c comment      %f fmt
    }

    # For each track...
    set idx 1
    foreach row $tracks {
        # Edit these.
        set artist  "The Chemical Brothers" ;# [lindex $row 0]
        set album   "Exit Planet Dust"
        set disc    ""
        set track   [format %02d $idx]
        set title   $row ;# [lindex $row 1]
        set comment ""   ;# [lindex $row 2]
        set fmt     ogg

        # Prepare a substitution table for [tmplsubst].
        set data {}
        foreach {key val} $substmap {
            set val [set $val]
            if {$val ne ""} {
                set val [string map $charmap [string tolower $val]]
                lappend data $key $val
            }
        }

        # Calculate the file names.
        set infile  [tmplsubst $in_tmpl  $data]
        set outfile [tmplsubst $out_tmpl $data]

        # Calculate the command line.
        switch -- $fmt {
        ogg {
            set cmdline [list oggenc $infile -o $outfile -q 5 -Q]
            foreach {flag elem} {-a artist -l album -t title
            -N track -c comment} {
                set val [set $elem]

                if {$val ne ""} {
                    switch -- $elem {
                    comment {
                        # Xmms compatibility.
                        set val =$val
                    } track {
                        # Xmms compatibility.
                        if {$disc ne ""} {
                            set val $disc.$val
                        }
                    }}

                    lappend cmdline $flag $val
                }
            }
        } mp3 {
            set cmdline [list lame -h -b 192 --quiet]
            foreach {flag elem} {--ta artist --tl album --tt title
            --tn track --tc comment} {
                if {[set elem] ne ""} {
                    lappend cmdline $flag [set elem]
                }
            }
        } default {
            error "Unknown format \"$fmt\""
        }}

        # Make sure the output directory exists.
        if {![file exists [file dirname $outfile]]} {
            file mkdir [file dirname $outfile]
        }

        # Do it.
        puts -nonewline "Encoding $outfile"
        flush stdout
        eval exec $cmdline
        puts ""

        incr idx
    }
}

# encode {
#     {"Filter & The Crystal Method"      "(Can't You) Trip Like I Do"}
#     {"Marilyn Manson & Sneaker Pimps"   "Long Hard Road Out of Hell"}
#     {"Orbital & Kirk Hammett"           "Satan"                     }
#     {"Korn & The Dust Brothers"         "Kick the P.A."             }
#     {"Butthole Surfers & Moby"          "Tiny Rubberband"           }
#     {"Metallica & DJ Spooky"            "For Whom the Bell Tolls\
#                                          (The Irony of It All)"     }
#     {"Stabbing Westward & Wink"         "Torn Apart"                }
#     {"Mansun & 808 State"               "Skin Up Pin Up"            }
#     {"Prodigy & Tom Morello"            "One Man Army"              }
#     {"Silverchair & Vitro"              "Spawn"                     }
#     {"Henry Rollins & Goldie"           "T-4 Strain"                }
#     {"Incubus & DJ Greyboy"             "Familiar"                  }
#     {"Slayer & Atari Teenage Riot"      "No Remorse (I Wanna Die)"  }
#     {"Soul Coughing & Roni Size"        "A Plane Scraped Its Belly\
#                                          On a Sooty Yellow Moon"    }
# }

encode {
    "Leave Home"
    "In Dust We Trust"
    "Song to the Siren"
    "Three Little Birdies Down Beats"
    "Fuck Up Beats"
    "Chemical Beats"
    "Chico's Groove"
    "One Too Many Mornings"
    "Life is Sweet"
    "Playground for a Wedgeless Firm"
    "Alive Alone"
}

# vim: set ts=4 sts=4 sw=4 tw=80 et:
