#include "svg.h"

double startX, startY, width, height;
int cols, rows;

void CardSpec(double sx, double sy, double dx, double dy, int c, int r) {
	startX = sx; startY = sy; width = dx; height = dy;
	cols = c; rows = r;
}

//	void f10a4_1() { CardSpec(14, 11, 91, 55, 2, 5); }
//	void f10a4_2() { CardSpec(18.6, 21.2, 86.4, 50.8, 2, 5); }
void f8a4_5()  { CardSpec(8, 10.5, 97, 69, 2, 4); }

void init() {
}

void drawFrame() {
	strokeWeight(0.1);
	stroke(bw1(0));
  noFill();
	rect(0, 0, width, height);
}

double branches[][3] = { { 1,      0.7,       0}     // 幹
                       , { 0.45,   0.5,      -80}    // 左の枝
                       , { 0.55,   0.45,      75} }; // 右の枝
      
void generate(double ratio, int d, double x, double y, double len, double angle) {
  double x1, y1;
  int i;

  if (d<=0) return;
  int color = hsb1(ratio+d/10.0, 1, 1);     /* 色 */
  stroke(color);
  x1 = x + len * cos360(angle);
  y1 = y + len * sin360(angle);
  line(x, y, x1, y1);
      
  for (i = 0; i < 3; i++) {
    double r = branches[i][0];
    generate(ratio, d-1,
             x * (1 - r) + x1 * r, y * (1 - r) + y1 * r,
             len * branches[i][1], angle + branches[i][2]);
  }
}

void drawCard(int n, int i, int j, double ratio) {
	drawFrame();  // for debug, comment out

	noStroke();
	fill(hsb360(ratio*360, 100, 100));
	textFont("MS-Mincho", 8);
	text("讃岐　太郎", 10, 30);

	textFont("Times New Roman", 8);
	fill(hsb360(ratio*360+90, 100, 100));
	text("Taro Sanuki", 10, 50);
    
	noFill();
  pushMatrix();
  translate(width-40, 25);
  strokeWeight(1);
  branches[0][2] = 5 * n - 20;
  generate(ratio, 5 /* 再帰の深さ */, 0, 30, 18, -60);
  popMatrix();
}

int main(void) {
	int i, j, n=0;
	double x;
	a4Portrait();
	start();
	init();
	f8a4_5();
  x = startX;
	for (i=0; i<cols; i++) {
		double y = startY;
		for (j=0; j<rows; j++, n++) {
			pushMatrix();
			translate(x, y);
			drawCard(n, i, j, (double)n/(cols*rows));
			popMatrix();
			y += height;
		}
		x += width;
	}
	finish();

  return 0;
}

