#! /usr/bin/perl

# gcc -save-temps -fomit-frame-pointer -Os -Wall -c jpg.c
# convert: .data -> .text
# ## add: .code16gcc
# convert: .local/.comm foo,bar,??? -> foo: .space bar,0
# remove: .size, .type, .align
# remove .section .note...
# remove .ident
# replace getword

sub fix_getword;

@f = (<>);

$getword = `cat getword`;

for (@f) {
  undef $_ if /^\s*\.(size|align|p2align|text|section|ident|local|data|file)/;
  $_ = "\n" if /^\s*\.type/;
  if(/^\s*\.globl/) {
    push @globl, "\t$_";
    undef $_;
  }

  if(/^\s*\.comm\s+(\S+),(\d+),\d+\s*$/) {
    push @comm, ( "\n", "$1:\n", "\t.space\t$2,0\n" );
    undef $_;
  }
}

unshift @globl, ( "\t.file\t\"jpeg.S\"\n", "\t.text\n",
  # "\t\.code16gcc\n",
  "\n"
);

fix_getword;

$_ = join '', @globl, @comm, @f; s/\n{3,}/\n\n/g; @f = split /\n/;

print "$_\n" for @f;

for (qw ( getword )) {
  if($fixes{$_} != 1) {
    print STDERR "error: fix failed: $_\n"
  }
}


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
sub fix_getword
{
  for (@f) {
    if(/^getword:/ .. /^\s*ret\b/) {
      if(/^getword:/) {
        $_ = $getword;
        $fixes{getword}++;
      }
      else {
        undef $_;
      }
    }
  }
}

