#!/usr/bin/perl

#@filenames=`ls -1 *gif`;
#chomp @filenames;
#
#$numoffiles=@filenames;
#$i=0;
#while ($i<$numoffiles ) {
#    $from=$filenames[$i];
#    $to=$filenames[$i];
#    $to =~ s/9798_//;
#    print ($from, "   ", $to, "\n");
#    `mv $from $to`;
#    $i++;
#}


# select each file
# Deal only with the "table" line
# separate the line into rows
# separate the rows into fields
# change the data in each field

#system ("mkdir output") if (!-d "output");

my @filenames = `ls -1 srchtml/*html ` ;
#my @filenames = (<test2.html>);
chomp @filenames;


foreach $_ ( sort @filenames) {
    print "\n";
    print ;
    $outputfile= $_;
    $outputfile =~ s/srchtml\///;
    #print $outputfile;
    #print "\n";
    open (FILE, "> $outputfile" );
    dealwithfiles($_);
    #print FILE "$outputfile";
    close (FILE);
}


sub dealwithfiles {
    my @filelines = `cat $_` ;
    my $filename = $_;
    $filename =~ s/\.html$//;
    $filename =~ s/^srchtml\///;

    #foreach $_ (@filelines) {	# do this for each line
    foreach $line (@filelines) {	# do this for each line
	if ( $line =~ m/pspwordsmaller.gif/ ) {
		$line =~ s/pspwordsmaller.gif/med\/$filename.gif/ ;
		$line =~ s/http:\/\/www.powersportspro.com\//$filename.gif/;
	}


        if ( $line =~ m/<TABLE/ ) {
#	    print FILE "it *DID* match TABLE";
#           @rows = split(/<TR>/);
            @rows = split /<TR>/, $line;
	    $numofrows = @rows;
	    $count=0;
	    while ( $count < $numofrows) {

            #foreach $row  (@rows) {	#do this for each row
	        $row = $rows[$count];	
		if ($count>0) {
		    $row = "<TR>".$row;
		}
		if ( $row =~ m/ISBN/ ) {    # match ISBN 
		    #print FILE "<tr><td>$count<td>desc.<td>part num.";
#		    print FILE "\n";
#		    print FILE "\n";
#		    print FILE $row;
#		    print FILE "\n";
#		    print FILE "\n";
		    #($itemnumber, $description, $partnumber) =~ m/(.*<TD>)(.*<TD>)(.*)/, $row ;
		    ($tr, $itemnumber, $description, $partnumber) = split /<TD/, $row ;

		    $itemnumber =~ s/<A HREF.*?>//;
		    $itemnumber =~ s/<\/A>//;
		    $description =~ s/<A HREF.*?>//;
		    $description =~ s/<\/A>//;
                    $partnumber =~ s/<A HREF.*ISBN=//;
                    $partnumber =~ s/&.*<\/A>//;
		    print FILE $tr;
		    print FILE "<TD";
		    print FILE $itemnumber;
		    print FILE "<TD";
                    print FILE $description;
		    print FILE "<TD";
                    print FILE $partnumber;
                    # print $partnumber;
                } else {
                    print FILE $row ; # print the rows that don't match
                    #print FILE "didn't match ISBN" ;
                }	# end of if m/ISBN
		print FILE "\n\n";
	    	#print FILE "<TR>";
	    $count ++;
	    }		# end of foreach rows

        } else {
            print FILE $line;  # print the lines that don't match
            #print FILE "didn't match TABLE";
        }  # end of m/TABLE

    }	# end of foreach filelines
}	# endo of dealwith files

