/ p5.js / P_3_1_3_01

// P_3_1_3_01
// 
/**
 * analysing and sorting the letters of a text 
 * changing the letters alpha value in relation to frequency
 *
 * MOUSE
 * position x          : interpolate between normal text and sorted position
 *
 * KEYS
 * 1                   : toggle alpha mode
 * s                   : save png
  */

var joinedText;

var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZÉÈÔ',.;:!? ";
counters = [alphabet.length];

var charSize;
var charColor = 0;
var posX, posY;
var drawAlpha = true;

function preload(){
  lines = loadStrings("perec.txt");
}

function setup() {
  createCanvas(780, 780);
  
  joinedText = join(lines, " ");
  textFont("Arial");
  textSize(10);
  countCharacters();
}

function draw() {
  textFont("Arial");
  background(255);
  noStroke();
  smooth();

  posX = 20;
  posY = 40;

  // go through all characters in the text to draw them  
  for (var i = 0; i < joinedText.length; i++) {
    // again, find the index of the current letter in the alphabet
    var s = str(joinedText.charAt(i)).toUpperCase();
    var uppercaseChar = s.charAt(0);
    var index = alphabet.indexOf(uppercaseChar);
    if (index < 0) continue;
    if (drawAlpha) fill(87, 35, 129, counters[index]*3);
    else fill(87, 35, 129);
    textSize(18);
    var sortY = index*20+40;
    var m = map(mouseX, 50,width-50, 0,1);
    m = constrain(m, 0, 1);
    var interY = lerp(posY, sortY, m);
    text(joinedText.charAt(i), posX, interY);
    posX += textWidth(joinedText.charAt(i));
    if (posX >= width-200 && uppercaseChar == ' ') {
      posY += 30;
      posX = 20;
    }
  }
}

function countCharacters(){
  for (var i = 0; i < joinedText.length; i++) {
    // get one char from the text, convert it to a string and turn it to uppercase
    var c = joinedText.charAt(i);
    var s = str(c);
    s = s.toUpperCase();
    // convert it back to a char
    var uppercaseChar = s.charAt(0);
    // get the position of this char inside the alphabet string
    var index = alphabet.indexOf(uppercaseChar);
    // increase the respective counter
    if (index >= 0) counters[index]++;
  }
}

function keyTyped(){
  if (key == 's' || key == 'S') save("P_3_1_3_01.png");

  if (key == '1') drawAlpha = !drawAlpha;
}