#!/usr/bin/perl
#Gifloop 1.0
#This program copyright HomeCom Communications, 1996.
#This program may not be modified from its original form without the prior
#consent of HomeCom Communications.
#This program may not be used for any type of commercial purpose whatsoever
#without the prior consent of HomeCom Communications.

#
#Get filename and number of times to loop from command line
#
($filename,$l) = @ARGV;

#
#Check for correct usage
#
if (@ARGV < 2) {
   die ("Usage: gifanim path_to_anim number_of_times_to_loop\n");
}
if ($l < 0 || $l > 65535) {
   die ("The looping count must be between 0 and 65535!\nGIF Anim unchanged.\n");
}

#
#Open file and the new version to be output
#
if (-e $filename) {
   open (IN, "$filename");
   open (OUT,">$filename.new");
} else {
   die ("$filename does not exist!\n");
}

#
#Make sure it's a gif89a file
#
sysread (IN, $buf, 6);

if ($buf ne "GIF89a") {
   die ("This is not a GIF89a file!\n");
} else {
   syswrite (OUT, $buf, 6);
}

#
#Read some misc stuff
#
sysread (IN, $buf, 4);
syswrite (OUT, $buf, 4);

#
#Read number of colors
#
sysread (IN, $buf, 1);
$buf2 = unpack("C",$buf);
$size = 2 ** ($buf2 - (int($buf2 / 8) * 8) + 1);
print "Color table has $size colors.\n";
syswrite (OUT, $buf, 1);

#
#Read some more misc stuff
#
sysread (IN, $buf, 2);
syswrite (OUT, $buf, 2);

#
#Read colormap
#
sysread (IN, $buf, 3 * $size);
syswrite (OUT, $buf, 3 * $size);

#
#Figure out Netscape2.0 app block, including number of times to loop
#
print "Inserting Netscape 2.0 Application Extension for looping.\n";
$hi = int($l / 256);
$lo = $l - $hi * 256;
$buf = sprintf("%c%c%cNETSCAPE2.0%c%c%c%c%c","33","255","11","3","1",$lo,$hi,"0");
syswrite (OUT, $buf, 19);

#
#Read rest of gif
#
print "Decoding GIF...";
sysread (IN, $buf, 256);
$count = 0;
while (length($buf) == 256) {
   $count++;
   syswrite (OUT, $buf, 256);
   sysread (IN, $buf, 256);
   if ($count == 10) {
      print ".";
      $count = 0;
   }
}
syswrite (OUT, $buf, length($buf));
print "\n";
$buf = sprintf("%c%cGifloop by HomeCom%c",hex(21),hex(fe),"0");
syswrite (OUT, $buf, 21); 
