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

typedef struct {
  int fd;
  int size;
  int curr;
  unsigned char buf[BUFSIZ];
} *ReadChar, ReadCharItem;

#define readChar_alloc() (ReadChar)malloc(sizeof(ReadCharItem))

#define readChar_init(rc, _fd) { rc->size = rc->curr = 0; rc->fd = _fd; }

#define readChar(rc) (int)(rc->size == rc->curr? \
		             (rc->size = read(rc->fd, rc->buf, BUFSIZ))? \
			       rc->buf[(rc->curr = 1) - 1]: \
			       (rc->curr = 0) - 1: \
		             rc->buf[rc->curr++])

#define readChar_free(rc) free(rc);

#define DIGITS 4

char dp[] = { 0x03, 0x0c, 0x30, 0xc0 };
char bit[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };  


main(argc, argv)
     int argc;
     char *argv[];
{
  int fd;
  ReadChar rc;
  char xsize[DIGITS], ysize[DIGITS];
  int i, c;
  int w = 0, h = 0;
  
  if (argc > 1) {
    if ((fd = open(argv[1], O_RDONLY)) == NULL)
      { perror("open"); exit(0); }
    dup2(fd, 0);
  }

  rc = readChar_alloc();
  readChar_init(rc, 0);
  
  if (readChar(rc) != 'P' || readChar(rc) != '4' || readChar(rc) != '\n') {
    fputs("Unknown file format\n", stderr);
    exit(0);
  }
  i = 0;
  while ((c = readChar(rc)) != ' ' && i < DIGITS)
    xsize[i++] = c;
  if (c != ' ') {
    fputs("Picture is too wide\n", stderr);
    exit(0);
  }
  switch(i) {
  case 4:
    w = w + (xsize[i - 4] - '0') * 1000;
  case 3:
    w = w + (xsize[i - 3] - '0') * 100;
  case 2:
    w = w + (xsize[i - 2] - '0') * 10;
  case 1:
    w = w + (xsize[i - 1] - '0') * 1;
  }
  i = 0;
  while ((c = readChar(rc)) != '\n' && i < DIGITS)
    ysize[i++] = c;
  if (c != '\n') {
    fputs("Picture is too tall\n", stderr);
    exit(0);
  }
  switch(i) {
  case 4:
    h = h + (ysize[i - 4] - '0') * 1000;
  case 3:
    h = h + (ysize[i - 3] - '0') * 100;
  case 2:
    h = h + (ysize[i - 2] - '0') * 10;
  case 1:
    h = h + (ysize[i - 1] - '0') * 1;
  }
  printf("P4\n%d %d\n", w * 2, h);

  while(h-- > 0) {
    int j = 0, d = 0;
    for (i = 0; i < w; i++) {
      if (j == 0) {
	j = 8;
	c = readChar(rc);
      }
      j--;
      if (c & bit[j])
	d |= dp[j & 3];

      if ((j & 3) == 0) {
	putchar(d);
	d = 0;
      }
    }
    if ((j & 3) != 0)
      putchar(d);
  }
  fclose(stdout);
}
