#include <avr/pgmspace.h>
#include <SPI.h>

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Fonts/FreeSerif9pt7b.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
const char s[] PROGMEM = {
  "The Keyboard and Mouse examples are unique to the Leonardo, "
  "Micro and Due. They demonstrate the use of libraries that "
  "are unique to the board. And so on and so forth, for ever "
  "and ever, ad infinitum, unless we run out of storage or "
  "screen space or something like that. Who knows what will "
  "come first. Will we even get to read this? I doubt it "
  "somehow, as this is only a quick demonstration of the "
  "technique, rather than production-ready code. "
  "Yet, as if by magic, that does seem to work correctly. "
  "So I shall try toBreakItWithASuperLongWordBecauseILikeToParty. "
  "does that work? really? *really?* Very well then. :-) "
};

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3D ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
  Serial.begin(9600);
  display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setTextWrap(true);
  display.setCursor(0, 0);
  display.clearDisplay();

  int columns = 21;
  // room for 22 characters and a null-terminator
  char wrapped[columns + 2];
  uint16_t spos = 0;
  while (spos < sizeof(s)) {
    uint16_t size = min(columns + 1, sizeof(s) - spos);
    memcpy_P(wrapped, s + spos, size);
    wrapped[size] = 0;
    char* spc_ptr = strrchr(wrapped, ' ');
    if (spc_ptr != 0) {
      *spc_ptr = 0;
      spos += spc_ptr - wrapped + 1;
    } else {
      wrapped[columns] = 0;
      spos += columns;
    }
    Serial.println(wrapped);
    display.println(wrapped);
    display.display();
  }

  delay(10000);
}
void loop() {

}