#include "scploader.h"



SCProblem* scploader_load_scp(char* filespec) {

    int rows;
    int cols;
    FILE* f;
    char lineBuffer[SCPLOADER_MAX_LINE_LENGTH+2];
    char* check;
    int k,j,c;
    unsigned char val;
    int cost;
    SCProblem* scp=NULL;

    /*Check parameter*/
    if (filespec==NULL) goto fail;

    /*Open file*/
    f=fopen(filespec,"rt");
    if (f==NULL) goto fail;

    /*Read size*/
    check=fgets(lineBuffer,SCPLOADER_MAX_LINE_LENGTH,f);
    if (check==NULL) goto fail_close;
    sscanf(lineBuffer,"%d %d",&cols,&rows);

    /*Create SCP*/
    scp = scproblem_new(rows,cols);

    /*Costs*/
    check=fgets(lineBuffer,SCPLOADER_MAX_LINE_LENGTH,f);
    if (check==NULL) goto fail_free_close;

    j=0;
    check=strtok(lineBuffer,", ");
    if (check!=NULL && sscanf(check,"%d",&cost)>0) {
        scproblem_set_cost(scp,j,cost);
        j++;
    }
    
    while((check=strtok(NULL,", "))!=NULL && sscanf(check,"%d",&cost)>0) {
        scproblem_set_cost(scp,j,cost);
        j++;
    }

    /*Number of costs does not match*/
    if (j<cols) goto fail_free_close;

   
    

    for(k=0;k<rows;k++) {
        check=fgets(lineBuffer,SCPLOADER_MAX_LINE_LENGTH,f);
        if (check==NULL) goto fail_free_close;

        /*Line read, Tokenizing*/
        j=0;
        c=0;
        while(c<cols && j<SCPLOADER_MAX_LINE_LENGTH) {
            val=*(lineBuffer+j);
            if (val=='0' || val=='1') {
                scproblem_set(scp,k,c,val-48);
                c++;
            }
        j++;
        }
        if (c<cols) goto fail_free_close;
    }

    
    
    

    

    /*Everything OK*/
        fclose(f);
        return scp;

    /*Unified end (like Linux kernel modules*/
    fail_free_close:
        scproblem_delete(scp);
    fail_close:
        fclose(f);
    fail:
        return NULL;

}
