# get_all
# extracts useful fields into a single file to be read by reg.cgi

BEGIN {
	FS = " *\t"
	OFS = "\t"

	# collect processed registrar data into arrays
	get_sched("foo_sched")
	get_prof("foo_prof")
	get_descr("foo_descr")
	get_xlist("foo_xlist")

	# put everything into a single file
	put_all()
}

function get_descr(fn) {
	id = 1; dept = 2; crsnumber = 3; term = 4; area = 5; crstitle = 6; crsdesc = 7
	nct = 0
	while (getline < fn > 0) {
		ct[nct] = $0
		ct_dept[nct] = $dept
		ct_crsnumber[nct] = $crsnumber
		ct_area[nct] = $area
		ct_crsdesc[nct] = escape($crsdesc)
		ct_crstitle[nct] = escape($crstitle)
		#if (nct < 5) printf("ct: [%s] [%s] [%s] [%s]\n", 
		#	NF, ct_dept[nct], ct_crsnumber[nct], ct_crstitle[nct])
		nct++
	}
}

function get_prof(fn) {
	FS = "\t"
	id = 1; dept = 2; crsnumber = 3; term = 4; professor = 5; prereq = 6  # prereq unused
	while (getline < fn > 0) {
		prof[$dept,$crs] = escape($professor)
	}
}

function get_sched(fn) {
	#9932    AAS      345    S06-07  S01     01:30 PM        04:20 PM        T       FIRES B06L
	id = 1; dept = 2; crs = 3; term = 4; format = 5; beg = 6; end = 7; days = 8; loc = 9; course_number = 10
	FS = "\t"
	nst = 0
	while (getline < fn > 0) {
		if ($format !~ /[LSCU]/)	# ignore precepts & other odd formats
			continue
		$crs = trim($crs)
		time[$dept,$crs] = $beg "-" $end
		gsub(/ [AP]M/, "", time[$dept,$crs])
		day[$dept,$crs] = $days
		place[$dept,$crs] = $loc
		course_num[$dept,$crs] = $course_number
		#if (nst < 5) printf("st: [%s] [%s] [%s]\n", NF, $dept, $crs, time[$dept,$crs])
		nst++
	}
}

function get_xlist(fn) {
	FS = "\t"
	id = 1; dept = 2; crsnumber = 3; term = 4; area = 5; crstitle = 6; xlists = 7
	while (getline < fn > 0) {
		### no actions yet
	}
}

function put_all() {
	for (i = 0; i < nct; i++) {
		d = day[ct_dept[i],ct_crsnumber[i]]
		t = time[ct_dept[i],ct_crsnumber[i]]
		p = place[ct_dept[i],ct_crsnumber[i]]
		pf = prof[ct_dept[i],ct_crsnumber[i]]
		regnum = course_num[ct_dept[i],ct_crsnumber[i]]
		tip = ct_crsdesc[i] " &nbsp;<i>" pf "</i> " regnum
		printf("<span onmouseover=\"return tooltip('%s')\"; onmouseout=\"exit();\">%3s %4.4s %3.3s  %6.6s %s %-10.10s %s</span>\n", 
			tip, ct_dept[i], ct_crsnumber[i], ct_area[i], 
			d, t, p, ct_crstitle[i])
	}
}

function trim(s) {
	gsub(/ /, "", s)
	return s
}

function escape(s) {
	# these are reinterpreted as real quotes!!!
	# so this does no good at all.
	#gsub(/'"'"'/, "\\&#39;", s)
	#gsub(/"/, "\\&quot;", s)
	gsub(/'/, "", s)
	gsub(/"/, "", s)
	return s
}
