/*
    STB Generator
    Copyright (C) 2006 Gian-Carlo Pascutto
   
    File: sfile.c
    Purpose: STB file functions
*/

#include <stdlib.h>
#include <stdio.h>

#include "global.h"
#include "sfile.h"
#include "utils.h"

static void sf_name_gen(matsig_s *sig, char *wname, char *bname) {
    char wbuff[MAX_PATH], bbuff[MAX_PATH];
 
    convert_sig_to_string(sig, wbuff);
    strcpy(bbuff, wbuff);

    strcat(wbuff, ".stw");
    strcat(bbuff, ".stb");

    strcpy(wname, "STB/");
    strcpy(bname, "STB/");

    strcat(wname, wbuff);
    strcat(bname, bbuff);   
}

sfile_s * sf_open(matsig_s *sig) {
    FILE *tmp, *tmp2;
    sfile_s *res;
    char wname[MAX_PATH], bname[MAX_PATH];      

    sf_name_gen(sig, wname, bname);

    tmp  = fopen(wname, "r");
    tmp2 = fopen(bname, "r");

    if (tmp == NULL || tmp2 == NULL) {
        return NULL;
    }

    res = (sfile_s*)malloc(sizeof(sfile_s));

    if (!res) {
        printf("Out of memory.\n");
        exit(EXIT_FAILURE);
    }

    res->wh = tmp;
    res->bh = tmp2;
    
    return res;
}

sfile_s * sf_create(matsig_s *sig) {
    FILE *tmp, *tmp2;
    sfile_s *res;
    char wname[MAX_PATH], bname[MAX_PATH];      

    sf_name_gen(sig, wname, bname);

    tmp  = fopen(wname, "w+");
    tmp2 = fopen(bname, "w+");

    if (tmp == NULL || tmp2 == NULL) {
        printf("Error creating file.\n");
        exit(EXIT_FAILURE);
    }

    res = (sfile_s*)malloc(sizeof(sfile_s));

    if (!res) {
        printf("Out of memory.\n");
        exit(EXIT_FAILURE);
    }

    res->wh = tmp;
    res->bh = tmp2;
    
    return res;
}

void sf_close(sfile_s *s) {
    fclose(s->wh);
    fclose(s->bh);
    free(s);
}
