#!/usr/bin/pike
/*
 * slicer.pike
 *
 * Slices a png in NxM different pngs
 *
 * History:
 *      28/06/2019 Creation
 *      27/01/2024 Support transparency
 *
 * 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;
        mapping imagemapping;
        Image.Image image,alpha,cropped,croppedalpha;
        Image.Layer l;
        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");
        imagemapping=Image._load(origfilename);
        image=imagemapping["image"];
        alpha=imagemapping["alpha"];
        px=image->xsize()/a4w;
        py=image->ysize()/a4h;
        for(total=0,y=0;y<a4h;y++) {
                for(x=0;x<a4w;x++) {
                        total++;
                        cropped=image->copy(x*px,y*py,(x+1)*px-1,(y+1)*py-1,255,255,255);
                        croppedalpha=alpha->copy(x*px,y*py,(x+1)*px-1,(y+1)*py-1,255,255,255);
                        l=Image.Layer(cropped,croppedalpha,"normal");
                        l->set_offset(0,0);
                        outfilename=sprintf("%s_%05d.png",resprefix,total);
                        write("* Writing "+outfilename+"...\n");
                        Stdio.write_file(outfilename,Image.PNG.encode(l->image(),(["alpha":l->alpha()])));
                }
        }
        write(""+total+" slices written. Process finished.\n");
        return(0);
}