#include <perms.h>

//          Edinburgh IMP77 Compiler - Version 8.4
//
//     1  !
//     2  ! Care has to be taken both to detect the missing %recordformatspec,
//     3  ! and to insert it in the output at the right level!
//     4  !
//     5
//     6  %begin

int main(int argc, char **argv) { /*%begin*/
  _imp_enter(main);
  _imp_initialise(argc, argv);

  //     7
  //     8    %recordformatspec RECFM                                              ;! <--- *should* be re-inserted here
  //     9
  //    10    %routine DO SOMETHING NESTED

  void DOSOMETHINGNESTED(void) {
    _imp_enter(DOSOMETHINGNESTED);

    //    11                                                                          ! <--- don't want it to be reinserted here!
    //    12      %recordformat LISTFM(%integer val, %record (RECFM) %name LINK)

    struct LISTFM {
      union {
        struct {
          int VAL;
          struct RECFM *LINK;
        };
      };
    };

    //    13
    //    14      %own %record (LISTFM) this

    static struct LISTFM THIS;

    //    15
    //    16      print string("sizeof(this) = "); write(sizeof(this), 0); newline

    _imp_printf("%s", "sizeof(this) = ");
    _imp_WRITE(_imp_SIZEOF(THIS), 0);
    _imp_NEWLINE();

    //    17
    //    18    %end

    _imp_return;
    _imp_begin_backtrace(DOSOMETHINGNESTED);
    _imp_diagf("\nLocal Variables:\n\n");
    _imp_diagf("THIS = \"<RECORD>\"\n");
    _imp_end_backtrace();
  } /* end of DOSOMETHINGNESTED */

  //    19
  //    20    %recordformat RECFM(%integer I, J)                                   ;! <--- this is what determines the scoping level where recordformatspec is re-inserted

  struct RECFM {
    union {
      struct {
        int I;
        int J;
      };
    };
  };

  //    21
  //    22    DO SOMETHING NESTED

  DOSOMETHINGNESTED();

  //    23
  //    24  %endofprogram

  _imp_stop(0);
end_0:;
  _imp_begin_backtrace(main);
  _imp_diagf("\n\nArguments:\n\n");
  _imp_diagf("ARGC = %d\n", argc);
  _imp_diagf("ARGV @[%p]\n", argv);
  for (int i = 0; i < argc; i++) {
    _imp_diagf("  ARGV(%d) = \"%s\"\n", i, argv[i]);
  }
  if (argv[argc] == 0) {
    _imp_diagf("  ARGV(%d) = NULL\n", argc);
  } else {
    _imp_diagf("  ARGV(%d) = \"%s\"\n", argc, argv[argc]);
  }
  _imp_diagf("\nLocal Variables:\n\n");
  _imp_end_backtrace();
  _imp_stop(0);
}