/*
 *   Copyright (C) 2003-2005 Michael Niedermayer <michaelni@gmx.at>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program 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 General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
 
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "rw.h"
#include "filerw.h"

static uint64_t fsize(FILE *f){
    uint64_t cur= ftell(f);
    uint64_t size;
    
    fseek(f, 0, SEEK_END); //FIXME 64bit stuff?
    size= ftell(f);
    fseek(f, cur, SEEK_SET);
    
    return size;
}

static int fileIO(noe_RwContext *c, uint8_t *data, uint64_t pos, int len, int write){
    int i;
    noe_FileRwContext *p= (noe_FileRwContext *)c;

    for(i=0; i<p->fileCount; i++){
        if(p->end[i] > pos){
            int e;
            uint64_t currentLen= pos - p->end[i];
            if(currentLen > len) currentLen= len;
            if(currentLen <= 0) return -1;

            if(fseek(p->file[i], pos - (i ? p->end[i-1] : 0), SEEK_SET))
                return -1;

            if(write)
                e= fwrite(data, currentLen, 1, p->file[i]);
            else
                e= fread(data, currentLen, 1, p->file[i]);
            if(e!=1) return -1;
            
            len -= currentLen;
            data+= currentLen;
            pos += currentLen;
            if(len==0) return 0;
        }
    }
    return -1;
}

static void fileUninit(noe_RwContext *c){
    int i;
    noe_FileRwContext *p= (noe_FileRwContext *)c;

    if(c==NULL) return;

    for(i=0; i<p->fileCount; i++){
        fclose(p->file[i]);
    }
    free(p->file);
    free(p->end);
    memset(p, 0, sizeof(noe_FileRwContext));
    free(p);
}

noe_RwContext *noe_getFileRwContext(char **fileNames, int fileCount, char *access){
    int i;
    uint64_t pos;
    noe_FileRwContext *p= malloc(sizeof(noe_FileRwContext));
    noe_RwContext *c= (noe_RwContext *)p;

    c->parent= NULL;

    p->file= malloc(sizeof(FILE)*fileCount);
    p->end= malloc(sizeof(uint64_t)*fileCount);

    c->io= fileIO;
    c->uninit= fileUninit;

    pos=0;
    for(i=0; i<fileCount; i++){
        p->file[i]= fopen(fileNames[i], access);
        if(p->file[i]==NULL) goto fail;

        pos+= fsize(p->file[i]);
        p->end[i]= pos;
    }
    c->size= p->end[i-1];

    return c;

fail:
    fileUninit(c);
    return NULL;
}
