#
#	CS2SORT.AWK
#
#  -----------------------------------------------------------------------
#  Copyright 2007  Alfred Steffens Jr.
#  -----------------------------------------------------------------------
#  -----------------------------------------------------------------------
#    Copying Permission:
#
#    mscore 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.
#
#    mscore 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 mscore (see file called "COPYING"); if not, write to the Free
#    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
#    02111-1307  USA
#  ------------------------------------------------------------------------
#
#   Mscore release 1.1
#
#	Sort the score lines in a Csound score according to start time
#


BEGIN {
	lineno = 1
}


$1 ~ /;[;]*/ {
	next
}


$1 ~ /i(.)*/ {


	score_line[lineno] = $0
	lineno++
}



END {
	#
	#	the sorting begins
	#
	total_lines = lineno - 1

	#
	#	loop until each line has been placed
	#
	new_i = 1
	for (i=1; i<=total_lines; i++) {

		mintime = 100000000
		#
		#	begin sorting at the lines not sorted yet
		#
		for (j=1; j<=total_lines; j++) {

			#
			#	sort only lines that are still in the list
			#
			if (j in score_line) {

				#
				#	find the smallest start time
				#
				nerr = split(score_line[j], score_items, " ")

				if (score_items[2] < mintime) {
					#
					#	save the new min time
					#
					mintime = score_items[2]
					minline = j
				}

			} # if -- j in score_line

		} # for -- j

		#
		#	re-locate the min line found
		#
		#
		#	append this line to the new list
		#
		sorted_lines[new_i] = score_line[minline]
		new_i++
		#
		#	remove it from the old list
		#
		delete score_line[minline]

	} # for -- i


	#
	#	sorting done	--	print the results
	#

	for (i=1; i<=total_lines; i++) {
		print sorted_lines[i]
	}


}
#	--------------------------- END --------------------------------------



