#!/bin/perl

# Giffy script... take a pile of gifs and stuff them into an animated gif
#
# Use: gif1.pl file1 file2 ... filen
# Output-to: multi.gif
#
# Bugs: You can either have the time block or the repeat... not
#       both. I don't know why.
#
# Notes:
#       Gif format from ftp://www-vs.informatik.uni-ulm.de/pub/WebVideo/gif87a.txt
#
# Disclaimer:
#       No warranty of fitness for any purpose
#
# Author:
#       W. M. Connolley wmc@bas.ac.uk

$DELAY=0x01;
# Setup options
eval "\$$1=\$2" while $ARGV[0] =~ /^(\w+)=(.*)/ && shift;

# Output to multi.gif
open(OUT,"> multi.gif");

# Use IMAGEN so we know only to output header for first file
$IMAGEN=0;

# Loop through input files
while ($FILE=shift @ARGV) {

print "FILE: $FILE\n";
open(IN,$FILE);
read(IN,$in,6);

#
# GIF signature
#
$TYPE=unpack("a6",$in);
if ($TYPE ne "GIF87a") {print "This is $TYPE not a GIF87a file - continuing anyway\n"};
$in="GIF89a";
if (!$IMAGEN) {print OUT $in};

#
# Screen Description
#
read(IN,$in,7);
if (!$IMAGEN) {print OUT $in};
$W=vec($in,1,8)*256+vec($in,0,8);
$H=vec($in,3,8)*256+vec($in,2,8);
print "Screen width:  $W\n";
print "       height: $H\n";
$I=vec($in,4,8);
$M=$I>>7; $PIXEL=$I&&7+1;
$Ncols=2**$PIXEL;
print "M, bits-per-PIXEL, Ncols: $M, $PIXEL, $Ncols\n";

if ($M != 1) {die "Require global colour maps"};

#
# Global colour map
#
read(IN,$in,$Ncols*3);
if (!$IMAGEN) {print OUT $in};
if ($COLS) {for ($I=0;$I<$Ncols;$I++) 
  { print "#, $I, Red: ",vec($in,$I*3,8),
               "Green: ",vec($in,$I*3+1,8),
                "Blue: ",vec($in,$I*3+2,8),"\n" }};

# 
# Insert special looping block!
# # And the timer block
#

#$in=pack("c3 a11 c2 S c",33,255,11,"NETSCAPE2.0",3,1,10,0);
$in=pack("c3 a11 c2 c2 c",33,255,11,"NETSCAPE2.0",3,1,0350,3,0);
if (!$IMAGEN) {print OUT $in};

$in=pack("c8",0x21,0xF9,4,4,$DELAY,0,0,0);
# For some wierd reason the timer block prevents looping. Odd
# {print OUT $in};

#
# Now onto image #1
# Expect this not to read the full amount
#
$N=read(IN,$in,10000000);
print "Read $N bytes Image-1 descriptor and LZW encoded data\n";
print OUT substr($in,0,$N-1);

# Terminator
$T=substr($in,-1,1);
$T=unpack("a",$T);
if ($T ne ";") {print "Terminator is $T not \";\"\n"} else {print "Read terminator OK\n"};

$IMAGEN++;
close(IN);
}

$in=pack("c8",0x21,0xF9,4,0,$DELAY,0,0,0);
#{print OUT $in};
