/* sageCounts.c was originally generated by the autoSql program, which also 
 * generated sageCounts.h and sageCounts.sql.  This module links the database and
 * the RAM representation of objects. */

/* Copyright (C) 2014 The Regents of the University of California 
 * See kent/LICENSE or http://genome.ucsc.edu/license/ for licensing information. */

#include "common.h"
#include "linefile.h"
#include "jksql.h"
#include "sageCounts.h"


struct sageCounts *sageCountsLoad(char **row)
/* Load a sageCounts from row fetched with select * from sageCounts
 * from database.  Dispose of this with sageCountsFree(). */
{
struct sageCounts *ret;
int sizeOne;

AllocVar(ret);
ret->numExps = sqlSigned(row[1]);
strcpy(ret->tag, row[0]);
sqlSignedDynamicArray(row[2], &ret->expCounts, &sizeOne);
assert(sizeOne == ret->numExps);
return ret;
}

struct sageCounts *sageCountsLoadAll(char *fileName) 
/* Load all sageCounts from a tab-separated file.
 * Dispose of this with sageCountsFreeList(). */
{
struct sageCounts *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[3];

while (lineFileRow(lf, row))
    {
    el = sageCountsLoad(row);
    slAddHead(&list, el);
    }
lineFileClose(&lf);
slReverse(&list);
return list;
}

struct sageCounts *sageCountsCommaIn(char **pS, struct sageCounts *ret)
/* Create a sageCounts out of a comma separated string. 
 * This will fill in ret if non-null, otherwise will
 * return a new sageCounts */
{
char *s = *pS;
int i;

if (ret == NULL)
    AllocVar(ret);
sqlFixedStringComma(&s, ret->tag, sizeof(ret->tag));
ret->numExps = sqlSignedComma(&s);
s = sqlEatChar(s, '{');
AllocArray(ret->expCounts, ret->numExps);
for (i=0; i<ret->numExps; ++i)
    {
    ret->expCounts[i] = sqlSignedComma(&s);
    }
s = sqlEatChar(s, '}');
s = sqlEatChar(s, ',');
*pS = s;
return ret;
}

void sageCountsFree(struct sageCounts **pEl)
/* Free a single dynamically allocated sageCounts such as created
 * with sageCountsLoad(). */
{
struct sageCounts *el;

if ((el = *pEl) == NULL) return;
freeMem(el->expCounts);
freez(pEl);
}

void sageCountsFreeList(struct sageCounts **pList)
/* Free a list of dynamically allocated sageCounts's */
{
struct sageCounts *el, *next;

for (el = *pList; el != NULL; el = next)
    {
    next = el->next;
    sageCountsFree(&el);
    }
*pList = NULL;
}

void sageCountsOutput(struct sageCounts *el, FILE *f, char sep, char lastSep) 
/* Print out sageCounts.  Separate fields with sep. Follow last field with lastSep. */
{
int i;
if (sep == ',') fputc('"',f);
fprintf(f, "%s%c", el->tag, sep);
if (sep == ',') fputc('"',f);
fputc(sep,f);
fprintf(f, "%d%c", el->numExps, sep);
fputc(sep,f);
if (sep == ',') fputc('{',f);
for (i=0; i<el->numExps; ++i)
    {
    fprintf(f, "%d", el->expCounts[i]);
    fputc(',', f);
    }
if (sep == ',') fputc('}',f);
fputc(lastSep,f);
}

