# Awk script to convert MASM ".lst" file into an ".asm" file.

BEGIN { FS = "	"    # tab character
	lastaddr = "!No code generated!"
	headerfile = "\dev\nul"
	procname = "!No entry point specified!"
	lengthname = "@"

	print "; DO NOT ALTER THIS FILE"
	print ";   It is created automagically by an awk script"
	print ";   Just sit back and enjoy"
	print ""
	print "  .xlist"
	print "  include mvdm.inc"
	print "  include vddseg.inc"
	print "  .list"
	print ""

      }

/#### HEADERFILE=/ {
  i = index($0, "HEADERFILE=")
  headerfile = substr($0, i+11)

  print "; header information is in ["headerfile"]"

  print "/* "headerfile" -- automagic header file */" >headerfile
  print "/* This file is created by an awk script. */" >headerfile
  print "/* Do not modify it directly. */" >headerfile

}

/#### ENTRYPOINT=/ {
  procname = substr($0, index($0, "=") + 1)

  print " DefData EXPORT,SWAP,C"
  print "VOID "procname

  print "extern UCHAR "procname"[];" >headerfile
}

/#### LENGTH=/ {
  i = index($0, "LENGTH=")
  lengthname = substr($0, index($0, "=") + 1)
}

/#### LABEL=/ {
  labelname = substr($0, index($0, "=") + 1)

  # Now extract the value of the label
  print "#define "labelname" 0x"substr($1,2,4) >headerfile
}


/#### BEGIN EXTRACTION/,/#### END EXTRACTION/ {
  if (substr($1,1,1) == " ") {   # This tosses out the page headers

	# first, split the first column into space-delimited fields
	n = split(substr($1,8),line, " ") # space

	lastaddr = substr($1,2,4)

	# Now step through the fields
	for (i = 1; i <= n; i++) {

		# Ignore relocation markers
		if (line[i] == "R") continue;
		if (line[i] == "----") line[i] = "0000";

		# Kill any segment override marker
		if (line[i] ~ /:/) line[i] = substr(line[i], 1, 2) 

		# Now output the appropriate data statement
		if (length(line[i]) == 2) print " db 0"line[i]"h"
		if (length(line[i]) == 4) print " dw 0"line[i]"h"
		if (length(line[i]) == 8) print " dd 0"line[i]"h"
	    
	}
  } # if we need to worry
}

END {
  print " IF THIS BYTE - "procname" NE 0"lastaddr"h"
  print "   .ERR Code length incorrect."
  print " ENDIF"
  print " EndData EXPORT,SWAP,C"
  print " END"

  if (lengthname != "@")
    print "#define "lengthname" 0x"lastaddr >headerfile
}

