#!/usr/bin/env kjscmd

//
// Script to report info about an HTML file.
//

function parse_attrs( src )
{
    var attrs = new Array();
    var attr_name;
    var attr_value;

    while ( src.length > 0 ) {
	// Attr name
	var am = src.match( /^\s*(\w+)\s*(=?)\s*/ );
	attr_name = am[1];
	src = src.slice( am[0].length );
    
	// If attr has a value
	if ( am[2] == '=' ) {

	    if ( src.charAt(0) == '"' ) {
                vm = src.match( /(\"[^\"]*\")\s*/ );
		attr_value = vm[1];
		src = src.slice( vm[0].length );
	    }
	    else {
		vm = src.match( /(\S+)\s*/ );
		attr_value = vm[1];
		src = src.slice( vm[0].length );
	    }

	}
	else {
	    attr_value = null;
	}
	src.replace( /^\s*/m, '' );

	attrs.push( [ attr_name, attr_value ] );
    }

    return attrs;
}

function process_tag_img( src )
{
    var tag = src.match( /<\s*(img)\s*([^>]*)\s*>/i );
    var elem = tag[1];
    var attrs = parse_attrs( tag[2] );

    warn( 'Element: '+elem );
    for ( var i=0 ; i < attrs.length; i++ ) {
	warn( '\t    '+attrs[i][0]+' = '+attrs[i][1] );
    }
}

var file = application.args[0];
var text = System.readFile( file );
var imgs = text.match( /<\s*img\s*[^>]*\s*>/ig );

for ( var i=0 ; i < imgs.length ; i++ ) {
    process_tag_img( imgs[i] );
}
