/*
 * doit.c: Quick hack to play a sequence of GIF files.
 * 
 * Rob McCool
 *
 * This code is released into the public domain.  Do whatever 
 * you want with it.
 *
 */

#include <sys/types.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>

#define LASTCHAR 'j'

#define HEADER \
"Content-type: multipart/x-mixed-replace;boundary=ThisRandomString\n" \

#define RANDOMSTRING "\n--ThisRandomString\n"
#define ENDSTRING "\n--ThisRandomString--\n"
#define CTSTRING "Content-type: image/gif\n\n"

int main(int argc, char *argv[])
{
    struct stat fi;
    char fn[32];
    caddr_t fp;
    unsigned char x;
    int fd;

    if(write(STDOUT_FILENO, HEADER, strlen(HEADER)) == -1)
        exit(0);
    if(write(STDOUT_FILENO, RANDOMSTRING, strlen(RANDOMSTRING)) == -1)
        exit(0);

    x = 'a';

    while(1) {
        sleep(1);
        if(write(STDOUT_FILENO, CTSTRING, strlen(CTSTRING)) == -1)
            exit(0);
        sprintf(fn, "images/A%c.gif", (char) x);
        if( (fd = open(fn, O_RDONLY)) == -1)
            continue;
        fstat(fd, &fi);
        fp = mmap(NULL, fi.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
        if(fp == (caddr_t) -1)
            exit(0);
        if(write(STDOUT_FILENO, (void *) fp, fi.st_size) == -1)
            exit(0);
        munmap(fp, fi.st_size);
        close(fd);
        if(write(STDOUT_FILENO, RANDOMSTRING, strlen(RANDOMSTRING)) == -1)
            exit(0);
        if(x == LASTCHAR) goto thats_it;
        else ++x;
    }

    /* This goto is Marc's fault.  Marc digs goto. */

thats_it:
    exit (0);
}
