
/*                                                                       */
/*              へらへらアニメ プレイヤー                                */
/*                     Sat Jan 28 23:26:10 JST 1995    a.higuchi         */
/*                                                                       */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include "helplay.h"


static int read_block(int fd, unsigned char *buffer, int n)
{
    int a;
    do {
        a = read(fd, buffer, n);
        if (a == 0) return 0;
        buffer += a;
        n -= a;
    } while (n > 0);
    return 1;
}

static unsigned char buffer_prev[SIZE];

static void page_diff_table_init()
{
    int j;
    for (j=0; j<SIZE; j++) buffer_prev[j] = 0;
}

static void page_diff(unsigned char *buffer)
{
    int j;
    for (j=0; j<SIZE; j++){
        buffer[j] = buffer[j] ^ buffer_prev[j];
        buffer_prev[j] = buffer[j];
    }
}

static int load_file(int fd)
{
    int page_count;
    unsigned char buffer[SIZE*32];
    int i=0, j, s;
    
    if (read_block(fd, buffer, 12) == 0) return -1;
    if (strncmp("he1", buffer, 3) != 0) return -2;

    page_count =  buffer[8];
    page_count += buffer[9]  <<  8;
    page_count += buffer[11] << 16;
    page_count += buffer[12] << 24;
    page_count++;

    open_helahela_window(page_count);
    page_diff_table_init();
    do {
        if (i+32 < page_count){
            if (read_block(fd, buffer, SIZE*32) == 0) return -7;
            s = 32;
        }
        else {
            if (read_block(fd, buffer, (page_count-i)*SIZE) == 0) return -7;
            s = page_count-i;
        }
        for (j=0; j<s; j++){
            page_diff(buffer+j*SIZE);
            if (set_a_helahela_page(i+j, buffer+j*SIZE)){
                return 1;
            }
        }
        i += s;
    } while (i < page_count);
    return 0;
}

int main(int argc, char *argv[])
{
    int fd;
    int wait = 30;
    int arg_count = 1;
    char file_name[1024] = "";
    int x;
    
    wait = 100;
    while (arg_count < argc){
        if (strcmp(argv[arg_count], "-w") == 0){
            wait = atoi(argv[++arg_count]);
        }
        else {
            strcpy(file_name, argv[arg_count]);
        }
        arg_count++;
    }
    if (strlen(file_name) == 0){
        fd = 0;         /* stdin */
    }
    else {
        fd = open(file_name, O_RDONLY);
        if (fd == -1) exit(-1);
    }
    
    x = load_file(fd);
    if (x >= 0)
      play_helahela(wait);
    
    free_helahela();
    
    if (fd != 0) close(fd);
    return 0;
}

