#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "generate.h"

int wc;                                                                         
const char* allowedc = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM.,:;!?-'";

void randp(int n, int *p)
{
  for (int i=0;i<n;i++)
  {
    int j = rand() % (1 + i);
    p[i] = p[j];
    p[j] = i;
  }
}

void zprintf(const char *s)
{
  wc += strlen(s);
  if (strchr(s, '\n'))
    ++wc;
  printf("%s", s);
}

void printspaces(bool weird)
{
  static bool flag = false;
  if (!flag)
  {
    flag = true;
    return;
  }
  if (!weird)  
  {
    if (rand() & 1)
      zprintf(" ");
    else
      zprintf("\n");
  }
  else
  {
    int t = rand() & 7;
    if (t == 0)
      zprintf(" ");
    if (t == 1)
      zprintf("\n");
    if (t == 2)
      zprintf("  ");
    if (t == 3)
      zprintf("   ");
    if (t == 4)
      zprintf(" \n");
    if (t == 5)
      zprintf("\n ");
    if (t == 6)
      zprintf(" \n ");
    if (t == 7)
      zprintf("  \n  ");
  }
}

void outimage1(bool surr, int ww, int hh, bool spaced)
{
  printspaces(spaced);
  zprintf("(image");
  static char s[3][128];
  sprintf(s[0], "width=%d", ww);
  sprintf(s[1], "height=%d", hh);
  if (surr)
    strcpy(s[2], "layout=surrounded");
  else
    strcpy(s[2], "layout=embedded");
  int p[3];
  randp(3, p);
  for (int i=0;i<3;i++)
  {
    printspaces(spaced);
    zprintf(s[p[i]]);
  }
  printf(")");
}

void outimage2(int ww, int hh, int dx, int dy, bool spaced)
{
  printspaces(spaced);
  zprintf("(image");
  static char s[5][128];
  sprintf(s[0], "width=%d", ww);
  sprintf(s[1], "height=%d", hh);
  strcpy(s[2], "layout=floating");
  sprintf(s[3], "dx=%d", dx);
  sprintf(s[4], "dy=%d", dy);
  int p[5];
  randp(5, p);
  for (int i=0;i<5;i++)
  {
    printspaces(spaced);
    zprintf(s[p[i]]);
  }
  zprintf(")");
}

void rands(int l, char* buffer)
{
  int N = strlen(allowedc);
  for (int i=0;i<l;i++)
    buffer[i] = allowedc[rand() % N];
  buffer[l] = 0;
}

void printrands(int l)
{
  static char buffer[8192];
  rands(l, buffer);
  zprintf(buffer);
}