#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <strings.h>

char **argvec;

static int blocksize;
static int padsize;
static char *buf;
static int ifill;

static void padwrite(void)
{
 int nw;

 if (ifill % padsize)
  { bzero(buf+ifill,padsize-(ifill%padsize));
    ifill = ((ifill / padsize) + 1) * padsize;
  }
 nw = write(1,buf,ifill);
 if (nw < 0)
  {
#ifdef HAVE_STRERROR
    fprintf(stderr,"%s: write error: %s\n",argvec[0],strerror(errno));
#else
    fprintf(stderr,"%s: write error: ", argvec[0]);
    perror(errno);
    fprintf(stderr,"\n");
#endif
    exit(1);
  }
 if (nw != ifill)
  { fprintf(stderr,"%s: short write (%d instead of %d)\n",argvec[0],nw,ifill);
    exit(1);
  }
 ifill = 0;
}

int main(int, char **);
int main(int ac, char **av)
{
 int nr;

argvec=av;
 if ((ac < 2) || (ac > 3))
  { fprintf(stderr,"Usage: %s blocksize [padsize]\n",argvec[0]);
    exit(1);
  }
 blocksize = atoi(av[1]);
 if (blocksize < 1)
  { fprintf(stderr,"%s: invalid blocksize, must be >= 1\n",argvec[0]);
    exit(1);
  }
 buf = malloc(blocksize);
 padsize = (ac > 2) ? atoi(av[2]) : 1;
 if (padsize < 1)
  { fprintf(stderr,"%s: invalid padsize, must be >= 1\n",argvec[0]);
    exit(1);
  }
 if (padsize > blocksize)
  { fprintf(stderr,"%s: invalid padsize, must be < blocksize\n",argvec[0]);
    exit(1);
  }
 if (blocksize % padsize)
  { fprintf(stderr,"%s: invalid padsize, must divide blocksize\n",argvec[0]);
    exit(1);
  }
 ifill = 0;
 while (1)
  { nr = read(0,buf+ifill,blocksize-ifill);
    if (nr < 0)
     {
#if HAVE_STRERROR
       fprintf(stderr,"%s: input read error: %s\n",argvec[0],strerror(errno));
#else
       fprintf(stderr,"%s: input read error: ",argvec[0]);
       perror(errno);
       fprintf(stderr,"\n");
#endif
       if (ifill > 0) padwrite();
       exit(1);
     }
    if (nr == 0)
     { if (ifill > 0) padwrite();
       exit(0);
     }
    ifill += nr;
    if (ifill > blocksize)
     { fprintf(stderr,"%s: BUGCHECK: ifill > blocksize\n",argvec[0]);
       abort();
     }
    else if (ifill == blocksize)
     { padwrite();
     }
  }
}


