#include <stdio.h>
#include <fcntl.h>

static int
getfdline (int fd, char *buf, int buflen)
{
  char *ptr = buf;

  buflen--;

  while (buflen > 0)
    {

      read (fd, ptr, 1);
      *(ptr + 1) = 0;
      buflen--;

      if (*ptr == '\n')
        {
          if (*buf == '#')
            {
              ptr = buf;
            }
          else
            {
              return 1;
            }
        }
      else
        ptr++;
    }

  return 0;
}



main (int argc, char *argv[])
{
  int nx, ny;
  int i, j;
  int m;
  int w, bw, h;
  int sw, sh, sbw, shc, swc;
  int infd;
  int *outfd;
  char filename[1024];
  char lbuf[1024];
  unsigned char *buf, *ptr;

  infd = 0;
  nx = atoi (argv[3]);
  ny = atoi (argv[4]);

   mkdir ("split.tmp");
  
  
  w = atoi (argv[1]);
  h = atoi (argv[2]);

  j = 0;

  sh = h / ny;
  sw = w / nx;
  bw = w * 3;
  sbw = sw * 3;

  outfd = (int *) malloc (sizeof (int) * nx);
  buf = (unsigned char *) malloc (bw);

  while (h >= sh)
    {

	printf("%d/%d (%d)\n",j,ny,h);
      for (i = 0; i < nx; ++i)
        {
          sprintf (filename, "split.tmp/split.%d.%d.ppm", i, j);
          outfd[i] = open (filename, O_CREAT | O_WRONLY | O_TRUNC, 0666);
          sprintf (lbuf, "P6\n%d %d\n255\n", sw, sh);
	  write(outfd[i],lbuf,strlen(lbuf));
        }

      shc = sh;

      while (shc--)
        {
	int toread=bw;
	char *ptr=buf;

	while (toread) {
          int red=read (infd, ptr, toread);
	toread-=red;
	ptr+=red;
	}

	ptr=buf;

          for (i = 0; i < nx; ++i)
            {
              write (outfd[i], ptr, sbw);
              ptr += sbw;
            }
        }
      for (i = 0; i < nx; ++i)
        {
          close (outfd[i]);
        }

      h -= sh;
      j++;
    }


  close (infd);
}
