#!/usr/bin/perl

# read in all of the html file names
 @files = <m*/*.html>;

#@files = <test*.html>;

# For each file,
for (@files) {

    $infile = $_;
@filename = split /\//, $infile;
$outfile = "$filename[0]/new_$filename[1]";

open (INFILE, "$infile") || die "problem opening $infile\n";

# Read it into an array

@file = <INFILE>;

close INFILE;

$acknowledgement = '<hr>Chemistry by OpenStax is licensed under Creative Commons Attribution License v4.0.  Download for free at <a href="http://cnx.org/contents/85abf193-2bd2-4908-8563-90b8a7ac8df6@12.1">http://cnx.org/contents/85abf193-2bd2-4908-8563-90b8a7ac8df6@12.1</a>';

$file[1] =~ s/\<\/head\>/\<link rel=\"stylesheet\" type=\"text\/css\" href=\"..\/openstax.css\"\>\<\/head\>/;

$file[3] =~ s/\<div data-type=\"document-title\"/\<h2/;
$file[3] =~ s/div/h2/;

# check for intro file
if (index($file[3], "introduction") != -1) {
    $file[4]="";
    $file[5]=~s/<div data-type=\"abstract\">/<details><summary>Summary<\/summary>/;
    $j=6;
} else {
    $file[3]=~s/<div data-type=\"abstract\">/<details data-type=\"abstract\"><summary>Objectives<\/summary>/;
    $j=4;
}

for $i ($j..$#file) {
    if (index($file[$i],"\/div") != -1) {
	$file[$i]=~ s/<\/div>/<\/details>/;
	last;
    }
}

$i = 0;

foreach (@file) {
    $_ =~ s/\"\/resources\/[[:alnum:]]+\//\"/g;
    $_ =~ s/\"\/contents\/[[:alnum:]|-]+#/\"|#/g;
    $_ =~ s/<cnx-pi[^<]*<\/cnx-pi>//g;
    $_ =~ s/<div data-type=\"newline\"><br\/><\/div>//g;
    # Look for solutions to questions 
    if (index($_, "<div data-type=\"solution") != -1) {
	$_ =~ s/<div/<details/;
	$_ =~ s/>/><summary>Solution<\/summary>/;
	$j = $i+1;
	# Find the end of the solution
	for $k ($j..$#file) {
	    if (index($file[$j],"/div")) {
		if ($file[$j+1] eq "</div>") {
		    #Close the solution
		    $file[$j+1] =~ s/<\/div>/<\/details>/;
		    last;
		}
	    }
	}
    }
    elsif (index($_, "</body>") != -1) {
	# Add license to end of each page
	$_ =~ s/<\/body>/$acknowledgement <\/body>/;
    }
    $i++;
}

$outfile=$infile;

open (OUTFILE, "> $outfile") || die "problem opening $outfile\n";

print OUTFILE @file; 
    
}
