/* This file is part of the KDE libraries
    Copyright (c) 2001 Waldo Bastian <bastian@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 as published by the Free Software Foundation.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <qstring.h>
#include <qfile.h>
#include <qptrlist.h>
#include <qimage.h>
#include <qapplication.h>


int
main(int argc, char *argv[])
{
   QApplication a(argc, argv, false);
   if (argc != 3)
   {
      fprintf(stderr, "Usage: kimage_concat <basefiles> <outputfile>\n");
      return 1;
   }
   QString basename = argv[1];
   QString outputname = argv[2];

   QPtrList<QImage> imageList;
   
   for(int i = 1; ;i++)
   {
      QString file;
      file.sprintf("%04d.png", i);
      file = basename + file;
      
      if (!QFile::exists(file)) break;
      
      imageList.append(new QImage(file));
   }

   int count = imageList.count();
   if (!count)
   {
      qWarning("Error: No images found.");
      return 1;
   }
   
   QImage *oldImage = imageList.at(0);
   
   int w = oldImage->width();
   if (w == 0)
   {
      qWarning("Error: Could not read image.");
      return 1;
   }
   
   int h = oldImage->height();
   
   // We use the height as the size and truncate any excess width.
   int total_h = h * count;
   int total_w = h;
   
   QImage *newImage = new QImage(total_w, total_h, 32);
   newImage->setAlphaBuffer(true);
   
   int offset = (( w - total_w ) / 2);
   offset = offset * oldImage->bytesPerLine() / w;
   int k = 0;
   int bytesPerLine = newImage->bytesPerLine();
   for(int i = 0; i < count; i++)
   {
      oldImage = imageList.at(i);
      for(int j = 0; j < h; j++)
      {
         memcpy( newImage->scanLine(k++), oldImage->scanLine(j)+offset, bytesPerLine);
      }
   }
   if (!newImage->save(outputname, "PNG"))
   {
      qWarning("Error: Could not write image");
      return 1;
   }
   return 0;
}

