/*** dupl.cpp  
*
*   increase image size by pixel replication.
*
***/

#include <stdio.h>
#include <stdlib.h>
#include "image.h"

int dupl(IMAGE *in, IMAGE *out, int hmag, int vmag);


int main(int argc, char *argv[])
{
	int magx, magy;
	IMAGE *in, *out;
	char *infile,*outfile;

	if (argc<3) {
		printf("usage: dupl infile outfile [magx] [magy]\n");
		printf("Expand image using pixel replication.\n");
		return -1;
	}
	infile=argv[1];
	outfile=argv[2];
	if (argc>3) sscanf(argv[3],"%d",&magx);
	else magx = 1;
	if (argc>4) sscanf(argv[4],"%d",&magy);
	else magy=magx;
	in = open_image(infile);
	if (!in) return -1;
	printf("input image: %s\n",infile);
	printf("image size: %d x %d\n",in->hlen,in->vlen);
	printf("pixel replication factors: %d x %d\n\n",magx,magy);
	if (magx<1 || magy < 1) {
		printf("illegal replication factors\n");
		return -1;
	}
	if (magx == 1 && magy == 1) {
		printf("no replication required\n");
		return -1;
	}
	out = make_image(outfile,in->hlen*magx,in->vlen*magy,in->type);
	printf("output image: %s\n",outfile);
	if (!out) {
		printf("error creating output file\n");
		return -1;
	}
	dupl(in,out,magx,magy);
	printf("image size: %d x %d\n",out->hlen,out->vlen);
	return 0;
}

int dupl(IMAGE *in, IMAGE *out, int hmag, int vmag)
{
	pixel *ibuf, *obuf;
	pixel *bp, *cp;
	int i, j, k, line;
	ibuf = make_buffer(in);
	obuf = make_buffer(out);
	if ((hmag<=0)||(vmag<=0)) return -1; // not allowed
	if (hmag*in->hlen > out->hlen) return -2; // image will not fit
	if (vmag*in->vlen > out->vlen) return -3;
	for (i=line=0;  i<in->vlen;  i++) {
		get_line(in,i,ibuf,in->type);
		bp = ibuf;
		cp = obuf;
		for (j=0; j<in->hlen; j++, bp++) {
			for (k=0; k<hmag; k++) *cp++ = *bp;
		}
		for (j=0; j<vmag; j++) put_line(out,line++,obuf,in->type);
	}
	free_buffer(obuf);
	free_buffer(ibuf);
	return 0;
}