#! /usr/bin/awk -f

# Massage Makefile into rules used for DVD extraction.

# Copyright 2007 Alexandre Oliva <lxoliva@fsfla.org>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, a copy can be downloaded from
# http://www.gnu.org/copyleft/gpl.html, or by writing to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

# This script arranges for subtitles that would have been displayed by
# each separate input to be displayed for the same extent of time,
# along with whatever other inputs would have displayed at that time.

BEGIN {
    subdir = "extract/";
}
/^[^- ]*-name = / {
    group = $3;
    gsub (/-name.*/, "");
    groups[$0] = group;
    print "INPUT-" group " = $(" $0 ")";
    if (names[$0])
	print "duplicate " name;
}
/^[^- ]* [+]= \$\(([a-z][-0-9a-z]*)\) # ([1-3]) (.*)$/ && groups[$1] != "" {
    var = $1;
    nmbr = sprintf ("%03i", ++count[var]);
    name = substr ($3, 3, length ($3) - 3);
    part = $5;
    args = gensub(/.* # [1-3] /, "", "", $0);
    pref = "$(" var "-name)-" nmbr
    nmrd = subdir pref ".avi";
    fnam = subdir name ".avi";

    if (names[name] || groups[name])
	print "duplicate " name;

    names[name] = 1;
    
    print name " = " fnam;
    print pref "-args = " args;
    print "FROM" part " += " nmrd;
    print "TOCLEAN += " fnam;
    print nmrd ": " fnam
    print "	ln -s $(notdir $<) $@";
    print fnam ":"
    print "	$(M" part "EXTRACT) $(" pref "-args) -o $@";
    next;
}
END {
    for (target in groups)
	if (groups[target])
	    print groups[target] ".avi small/" groups[target] ".avi: $(INPUT-" groups[target] ")";
}
