/* Author: Ing. Marek Paralic, PhD.
   We miss you in our lectures :)
 */

#include <superkarel.h>

#define SPEED 100

// declarations
void put_fib_num(void);
void move_back(void);
void copy_beepers(void);
void copy_beepers_skip_1(void);

int main(void) {
    turn_on("fibonacci.kw");
    set_step_delay(SPEED);
   
    // initialization: first two Fib numbers, F1 and F2
    put_beeper();
    step();
    put_beeper();
    step();
    while (front_is_clear()) {
        put_fib_num();
    }
    put_fib_num();
   
    turn_off();
    return 0;
}

// Karel puts to actual position number of beepers
// equal to the next number in Fib sequence, FibN
// before: Karel stands at an empty place and the previous
//         two positions are equal to FibN-1 and FibN-2
// after : Karel stands at position next to FibN (to the East)
void put_fib_num(void) {
    move_back();
    copy_beepers();
    move_back();
    copy_beepers_skip_1();
    while (beepers_present() && front_is_clear()) {
        step();
    }
}

// do one step back, but keep the original direction
void move_back(void) {
    set_step_delay(0);
    turn_left();
    turn_left();
    step();
    turn_left();
    set_step_delay(SPEED);
    turn_left();
}

// Karel copies every beeper from actual position
// to the next position
void copy_beepers(void) {
    pick_beeper();
    if (beepers_present()) {
        copy_beepers();      // recursive function call
    }
    put_beeper();
    step();
    put_beeper();
    move_back();
}

// Karel copies every beeper from actual position
// two positions to the East
void copy_beepers_skip_1(void) {
    pick_beeper();
    if (beepers_present()) {
        copy_beepers_skip_1(); // recursive function call
    }
    put_beeper();
    step();
    step();
    put_beeper();
    move_back();
    move_back();
}
