#!/usr/bin/pike
/*
 * slicer.pike
 *
 * Slices a png in NxM different pngs
 *
 * History:
 *      28/06/2019 Creation
 *
 * Author: Dario Rodriguez dario@softhome.net
 * This program is distributed under the terms of the GNU GPL v2.1+
 */

int
main(int argc, array(string) argv)
{
        int a4w,a4h;
        int px,py;
        string origfilename;
        string resprefix;
        int x,y,total;
        Image.Image img,cropped;
        string outfilename;
        if(argc<4 || (argc>1 && argv[1]=="--help")) {
                Stdio.werror("Syntax:  "+argv[0]+" <width_in_a4pages> <height_in_a4_pages> <origimage.png>\n");
                Stdio.werror("Example: "+argv[0]+" 4 2 orig.png\n");
                Stdio.werror("Example result: orig_0001.png ... orig_0008.png\n");
                return(1);
        }
        a4w=(int)argv[1];
        a4h=(int)argv[2];
        origfilename=argv[3];
        resprefix=(origfilename/".png")[0];
        write("* Loading "+origfilename+"...\n");
        img=Image.load(origfilename);
        px=img->xsize()/a4w;
        py=img->ysize()/a4h;
        for(total=0,y=0;y<a4h;y++) {
                for(x=0;x<a4w;x++) {
                        total++;
                        cropped=img->copy(x*px,y*py,(x+1)*px-1,(y+1)*py-1,255,255,255);
                        outfilename=sprintf("%s_%05d.png",resprefix,total);
                        write("* Writing "+outfilename+"...\n");
                        Stdio.write_file(outfilename,Image.PNG.encode(cropped));
                }
        }
        write(""+total+" slices written. Process finished.\n");
        return(0);
}