' _CreateBuildFile.bas
' create _build.bat
' include all *.bas from folder but not with an underscore in front.
' e.g. "_CreateBuildFile.bas"

' add your path to FreeBASIC (it's in the PATH on my box)
'const FBC_PATH as string = "fbc"
'const FBC_FLAG as string = "-w pedantic -lib"

ChDir ExePath()

redim as string files()
dim as string   file  = dir("*.bas")
dim as integer  nFiles

while len(file)
	if left(file,1)="_" then
		' ignore all files with "_"
	else
		redim preserve files(nFiles)
		files(nFiles) = file
		nFiles+=1
	end if
	file = dir()
wend

' sort the list
if nFiles>1 then
	dim as integer flag=1
	while flag=1
		flag=0
		for i as integer=0 to nFiles-2
			if left(files(i),1) > left(files(i+1),1) then
				swap files(i),files(i+1)
				flag=1
				exit for
			end if
		next
	wend
	dim as integer hFile = FreeFile()
	if open("makefile",for output,as #hFile) then
		? "error: can't create 'makefile' !"
		beep:sleep:end 1
	end if

	print #hFile, "FBC_PATH ?= fbc.exe"
	print #hFile, "FBC_FLAG ?= -w pedantic -lib"
		
	dim as string link0 = "$(FBC_PATH) $(FBC_FLAG) -x libwindow9.a"
	dim as string link
	for i as integer=0 to nFiles-1
		link &= " tmp/" & left(files(i),len(files(i))-4) & ".o"
	Next

	print #hFile, "libwindow9.a: " & mid(link,2)
	print #hFile, !"\9\9" & link0 & link &  !"\13\10"
	'print #hFile, !"\13\10"
	
	for i as integer=0 to nFiles-1
		print #hFile, "tmp/" & left(files(i),len(files(i))-4) & ".o: " & files(i)
		print #hFile, !"\9\9 $(FBC_PATH) -nodeflibs -c " & files(i) & " -o tmp/" & left(files(i),len(files(i))-4) & ".o" & !"\13\10"
	Next
	print #hFile, "clean:" & !"\13\10"
	print #hFile, !"\9\9" & "rm -f tmp/*.o"
	print #hFile, !"\9\9" & "rm libwindow9.a"
	close #hFile
else
	? "error: no *.bas files !"
	beep:sleep:end 2
end if
