#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    %reals %long
  //     3
  //     4    %integer rounds

  int ROUNDS = 0xFEFEFEFE;

  //     5    %real pi = 1.0

  double PI = __builtin_nan("");
  PI = 1.0;

  //     6
  //     7    !%on %event 9 %start
  //     8    !  print string("Cannot open file"); newline
  //     9    !  %stop
  //    10    !%finish
  //    11
  //    12    %integer i

  int I = 0xFEFEFEFE;

  //    13
  //    14    open input(1, "rounds.txt");   ! open file

  _imp_OPENINPUT(1, _imp_str_literal("rounds.txt"));

  //    15    select input(1)

  _imp_SELECTINPUT(1);

  //    16
  //    17    read(rounds)

  _imp_READ(((_imp_name){.address = &ROUNDS, .typeinfo = 1, .sizeinfo = sizeof(ROUNDS)}));

  //    18
  //    19    close input;                   ! close file

  _imp_CLOSEINPUT();

  //    20
  //    21    rounds = rounds + 2;           ! do this outside the loop

  ROUNDS = ROUNDS + 2;

  //    22
  //    23    %for i=2, 1, rounds %cycle

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

    //    24      %long %real x = -1.0 + 2.0 * (i & 1); ! allows vectorization

    double X = __builtin_nan("");
    X = -1.0 + 2.0 * (I & 1);

    //    25      pi = pi + (x / (2 * i - 1)); ! double / unsigned = double

    PI = PI + (double)(X / (2 * I - 1));

    //    26    %repeat

    goto L_0001;
  }

L_0002:;

//    27
//    28    pi = pi * 4

  PI = PI * 4;

  //    29    print fl(pi, 16);              ! print 16 decimal digits of pi

  _imp_PRINTFL(PI, 16);

  //    30    newline

  _imp_NEWLINE();

  //    31
  //    32  %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_bt_int(ROUNDS);
  _imp_bt_real(PI);
  _imp_bt_int(I);
  _imp_bt_real(X);
  _imp_end_backtrace();
  _imp_stop(0);
}