#include <perms.h>

//          Edinburgh IMP77 Compiler - Version 8.4
//
//     1  %begin

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

  //     2    %string (255) s

  _imp_string255 S;

  //     3    %integerfn fred(%integername i)

  int FRED(int *I) {
    _imp_enter(FRED);

    //     4      %integer total = 0

    int TOTAL = 0xFEFEFEFE;
    TOTAL = 0;

    //     5      %if charno(s, i) = 's'  %start

    if ((*_imp_CHARNO((_imp_string255 *)&S, *I)) != (115)) goto L_0001;

      //     6        %result = 0

    _imp_result(0);

    //     7      %finish

  L_0001:;

  //     8      total = 0

    TOTAL = 0;

    //     9      %for i = 1, 1, i %cycle

    // %for *I = 1, 1, *I %cycle
    {
      int _final = *I;
      if (invalid_for_loop(1, 1, _final)) _imp_signal(5, 1, 0, "Illegal cycle *I = 1, 1, *I");
      *I = 0;
    L_0002:
      if (*I == _final) goto L_0003;
      *I += 1;

      //    10        total = total + i

      TOTAL = TOTAL + *I;

      //    11      %repeat

      goto L_0002;
    }

  L_0003:;

  //    12      %result = total

    _imp_result(TOTAL);

    //    13    %end

    _imp_begin_backtrace(FRED);
    _imp_diagf("\n\nArguments:\n\n");
    _imp_diagf("I = %d\n", *I);
    _imp_diagf("\nLocal Variables:\n\n");
    _imp_bt_int(TOTAL);
    _imp_end_backtrace();
  } /* end of FRED */

  //    14    %integer x, y

  int X = 0xFEFEFEFE;
  int Y = 0xFEFEFEFE;

  //    15    s = "a string"

  _imp_strcpy(&S, _imp_strp(_imp_str_literal("a string")), /*max:*/ 255);

  //    16    y = 3

  Y = 3;

  //    17    x = fred(y)

  X = FRED(&Y);

  //    18  %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_diagf("S = \"%.*s\"\n", S.cstr.len, S.cstr.s);
  _imp_bt_int(X);
  _imp_bt_int(Y);
  _imp_end_backtrace();
  _imp_stop(0);
}