#!/usr/local/bin/perl
$cfile = $ARGV[0]; shift;
$hfile = $ARGV[0]; shift;
while (<>)
{
  if (/^#pragma segment/)
  {
    chop;
    split;
    if ($_[2] ne "Main" && $_[2] ne "ObjSupport")
    {
      $seglist{$_[2]} = $_[2];
    }
  }
}

open(CFILE,">$cfile") || die "$cfile";
open(HFILE,">$hfile") || die "$hfile";
print CFILE "#include \"numcode.h\"\n";
foreach $seg (keys(%seglist))
{
	$count++;
  printf CFILE "#pragma segment %s\n",$seg;
  printf CFILE "void __Seg%s(void);\n",$seg;
  printf CFILE "void __Seg%s(void){}\n",$seg;
}
print CFILE <<"EOF";
#pragma segment Main
void UnloadSegments(void);
void UnloadSegments(void)
{
#if __profile__
	return;
#endif
	if (!CantLock && LockCode) return;
#ifdef THREADING_ON
/*
	this is a short term solution to the stack corruption bug that occurs when segments that 
	a thread is using are unloaded
*/
	if (GetNumBackgroundThreads ()) return;
#endif
EOF
foreach $seg (keys(%seglist))
{
  printf CFILE "  UnloadSeg(__Seg%s);\n",$seg;
}
print CFILE "}\n";

$count += 2;	# code 1 and code 0
print HFILE "#ifndef NUM_CODE\n#define NUM_CODE $count\n#endif\n";
