' _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.exe"
'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("_build.bat",for output,as #hFile) then
      ? "error: can't create '_build.bat' !"
      beep:sleep:end 1
   end if
   print #hFile, "@set FBC_PATH=fbc.exe"
   print #hFile, "@set FBC_FLAG=-w pedantic -lib"
   print #hFile, "@if not exist tmp mkdir tmp"
   print #hFile, "@del /Q tmp\*.*"
   for i as integer=0 to nFiles-1
      print #hFile, "@echo compile: " & files(i)
      print #hFile, "@%FBC_PATH%" & " -nodeflibs -c " & files(i) & " -o tmp/" & left(files(i),len(files(i))-4) & ".o"
      print #hFile, "@if ErrorLevel 1 goto compileerror"
   next
   dim as string link = "%FBC_PATH% %FBC_FLAG% -x libwindow9.a"
   for i as integer=0 to nFiles-1
      link &= " tmp/" & left(files(i),len(files(i))-4) & ".o"
   next
   print #hFile, link

   print #hFile, "@if ErrorLevel 1 goto linkerror"
   print #hFile, "@echo #################"
   print #hFile, "@echo # no errors :-) #"
   print #hFile, "@echo #################"
   print #hFile, "@goto exit"

   print #hFile, ":linkerror"
   print #hFile, "@echo ################"
   print #hFile, "@echo # link error ! #"
   print #hFile, "@echo ################"
   print #hFile, "@goto exit"

   print #hFile, ":compileerror"
   print #hFile, "@echo ###################"
   print #hFile, "@echo # compile error ! #"
   print #hFile, "@echo ###################"
   print #hFile, "@goto exit"

   print #hFile, ":exit"
   print #hFile, "@pause"

   close #hFile
else
   ? "error: no *.bas files !"
   beep:sleep:end 2
end if

