#include <perms.h>

//          Edinburgh IMP77 Compiler - Version 8.4
//
//     1  %systemstring(127)%fnspec rtos(%real r,%integer n,m)

extern _imp_string127 RTOS(float R, int N, int M);

//     2
//     3  %systemstring(127)%fn rtof(%real x, %integer n)

extern _imp_string127 RTOF(float X, int N) {
  _imp_enter(RTOF);

  //     4    %real y,round

  float Y = __builtin_nanf("");
  float ROUND = __builtin_nanf("");

  //     5    %integer count=-99,sign=0

  int COUNT = 0xFEFEFEFE;
  COUNT = -99;
  int SIGN = 0xFEFEFEFE;
  SIGN = 0;

  //     6    %string(127) result=""

  _imp_string127 RESULT;
  _imp_strcpy(&RESULT, _imp_strp(_imp_str_literal("")), /*max:*/ 127);

  //     7    !
  //     8    %if x # 0 %start

  if ((X) == (0)) goto L_0001;

    //     9      x = -x %and sign = 1 %if x < 0

  if ((X) >= (0)) goto L_0002;
  X = -X;
  SIGN = 1;
L_0002:;

//    10     !Adjust X so that 1.0 <= rounded(X) < 10.0
//    11      count = 0;  round = 0.5\{^}n

  COUNT = 0;
  ROUND = _imp_REXP(0.5, N);

  //    12      y = 1.0-round

  Y = 1.0 - ROUND;

  //    13      %if x < y %start;  !ie rounded(X) < 1.0

  if ((X) >= (Y)) goto L_0003;

    //    14        count = count-1 %and x = x*10.0 %until x >= y

L_0004:;
  COUNT = COUNT - 1;
  X = X * 10.0;
  if ((X) >= (Y)) goto L_0005;
  goto L_0004;
L_0005:;

//    15      %finish %else %start

  goto L_0006;
L_0003:;

//    16        y = 10.0-round

  Y = 10.0 - ROUND;

  //    17        %while x >= y %cycle;  !ie rounded(X) > 10.0

L_0007:;
  if ((X) < (Y)) goto L_0008;

    //    18          count = count+1;  x = x/10.0

  COUNT = COUNT + 1;
  X = (double)(X / 10.0);

  //    19        %repeat

  goto L_0007;
L_0008:;

//    20      %finish

L_0006:;

//    21      x = -x %if sign # 0

  if ((SIGN) == (0)) goto L_0009;
  X = -X;
L_0009:;

//    22    %finish

L_0001:;

//    23    result = rtos(x,1,n)

  _imp_strcpy(&RESULT, _imp_strp(RTOS(X, 1, N)), /*max:*/ 127);

  //    24    result = result."@".itos(count,0)

  _imp_strassign(&RESULT, 127, "%S%s%S", _imp_strp(RESULT), "@", _imp_strp(_imp_ITOS(COUNT, 0)));

  //    25    %result = result

  _imp_result(*(_imp_string127 *)_imp_strp(RESULT));

  //    26  %end;  !flrtos

  _imp_begin_backtrace(RTOF);
  _imp_diagf("\n\nArguments:\n\n");
  if (__builtin_isnan(X))
    _imp_diagf("X = <UNASSIGNED REAL>\n");
  else
    _imp_diagf("X = %LE\n", (long double)X);
  _imp_diagf("N = %d\n", N);
  _imp_diagf("\nLocal Variables:\n\n");
  _imp_bt_real(Y);
  _imp_bt_real(ROUND);
  _imp_bt_int(COUNT);
  _imp_bt_int(SIGN);
  _imp_diagf("RESULT = \"%.*s\"\n", RESULT.cstr.len, RESULT.cstr.s);
  _imp_end_backtrace();
} /* end of RTOF */

//    27
//    28  %endoffile