#include <string>
#include <vector>
#include <iostream>

#include <time.h>
#include <stdlib.h>
using namespace std;

int main(int argc, char *argv[]) {

  if (argc != 3) {
    cerr << "Usage: pics2html <num-hour-split> <num-min-split>" << endl;

    cerr << "Reads from standard input, and outputs SHTML to standard output." << endl;
    cerr << "For example: " << endl;

    cerr << "    pics2shtml 10 10 < data.txt > include.shtml" << endl;
    cerr << "will split each hour into 10 parts (6 min each), and each minute" << endl;

    cerr << "into 10 parts (6 sec each).  Every 6 sec, a different picture will" << endl;
    cerr << "appear, but cycling every minute for 6 minutes, after which a" << endl;

    cerr << "different set of 10 pictures will be used." << endl;
    cerr << endl;

    cerr << "Standard input is interpreted as chunks, delimited by blank lines." << endl;
    cerr << "Each chunk corresponds to a possible outcome of the program." << endl;

    return 0;
  }

  time_t tim;
  time(&tim);

  srandom(tim);

  int Nmin, Nsec;
  int min[60], sec[60];

  sscanf(argv[1], "%d", &Nmin);
  sscanf(argv[2], "%d", &Nsec);

  int left = 60;
  int gap = 60/Nmin;

  for (int k = 0; k < Nmin; ++k) {

    left -= gap;
    min[k] = left;
  }

  gap = 60/Nsec;
  left = 60;

  for (int k = 0; k < Nsec; ++k) {

    left -= gap;
    sec[k] = left;
  }

  int total = Nmin*Nsec;
  vector<string> lines;

  // now read in the lines of pictures
  string line;
  string glob = "";
  while (getline(cin, line)) {

    if (line.size() == 0) {
      if (glob.size() != 0)

	lines.push_back(glob);
      glob = "";
    }
    else

      glob += " " + line;
  }
  if (glob.size() != 0)

    lines.push_back(glob);
  int Nlines_orig = lines.size();

  if (lines.size() > total) {
    cerr << "Insufficient space for images!  Slots = " << total << " but images = " << lines.size() << endl;
  }

  
  // now pad the back with random images to make it up to total
  cerr << "padding the back with " << total - lines.size() << " images" << endl;

  while (lines.size() < total)
    lines.push_back(lines[random()%Nlines_orig]);

  // now prepare the output
  // this is the header, to capture sec and min
  cout << "<!--#config timefmt='%S' -->" << endl;
  cout << "<!--#set var='sec' value='${DATE_LOCAL}' -->" << endl;

  cout << "<!--#config timefmt='%M' -->" << endl;
  cout << "<!--#set var='min' value='${DATE_LOCAL}' -->" << endl;

  cout << endl;
  
  // loop time
  for (int m = 0; m < Nmin; ++m) {

    cout << "<!--#";
    if (m != 0)

      cout << "el";
    cout << "if expr='${min} >= " << min[m] << "' -->" << endl;

    for (int s = 0; s < Nsec; ++s) {

      cout << "  <!--#";
      if (s != 0)

	cout << "el";
      cout << "if expr='${sec} >= " << sec[s] << "' -->" << endl;

      cout << "  " << lines[m*Nsec + s] << endl;
    }

    cout << "  <!--#endif -->" << endl;
  }
  cout << "<!--#endif -->" << endl;

  return 0;
}