/* * param.c * * Summary: Top level interface for reading parameter files. * * Author: David Hardy */ #include #include #include #include "param.h" #include "paramxp.h" #include "pdata.h" #include "error.h" int param_init(Param *p, Pbuf *pbuf) { /* init all pointers */ p->pbuf = pbuf; p->pdata = NULL; p->f = NULL; p->reader = NULL; p->type = 0; p->status = 0; /* allocate memory for parameter database */ p->pdata = (Pdata *) malloc(sizeof(Pdata)); if (p->pdata == NULL) { mdio_error("malloc() failed, file %s, line %d\n", __FILE__, __LINE__); p->status |= MDIO_ERR_MEMALLOC; return -1; } if (pdata_init(p->pdata, pbuf) != 0) { mdio_error("pdata_init() failed, file %s, line %d\n", __FILE__, __LINE__); p->status |= pdata_status(p->pdata); return -1; } return 0; } void param_destroy(Param *p) { /* free memory */ if (p->pdata) { pdata_destroy(p->pdata); free(p->pdata); } /* reset everything */ memset(p, 0, sizeof(Param)); } int param_open(Param *p, const char *fname, int type) { /* open parameter file */ p->f = fopen(fname, "r"); if (p->f == NULL) { mdio_error("fopen() failed, file %s, line %d\n", __FILE__, __LINE__); p->status |= MDIO_ERR_OPEN; return -1; } /* for now there is only one type of parameter file: XPLOR */ /* allocate memory for file reader and init */ if (type == PARAM_XPLOR) { p->reader = malloc(sizeof(Paramxp)); if (p->reader == NULL) { mdio_error("malloc() failed, file %s, line %d\n", __FILE__, __LINE__); p->status |= MDIO_ERR_MEMALLOC; return -1; } p->type = PARAM_XPLOR; if (paramxp_init((Paramxp *) p->reader, p->pdata, p->f) != 0) { mdio_error("paramxp_init() failed, file %s, line %d\n", __FILE__, __LINE__); p->status |= paramxp_status((Paramxp *) p->reader); paramxp_destroy((Paramxp *) p->reader); free(p->reader); p->reader = NULL; return -1; } } else { mdio_error("unsupported file type %d specified, file %s, line %d\n", type, __FILE__, __LINE__); p->status |= MDIO_ERR_UNSUPPORTED; return -1; } return 0; } int param_close(Param *p) { int retval = 0; /* destroy and free memory for file reader */ if (p->type == PARAM_XPLOR) { if (p->reader != NULL) paramxp_destroy((Paramxp *) p->reader); } else if (p->type != 0) { mdio_fatal("invalid file type %d, file %s, line %d\n", p->type, __FILE__, __LINE__); } free(p->reader); p->reader = NULL; p->type = 0; /* close the file handle */ if (p->f != NULL && fclose(p->f)) { mdio_error("fclose() failed, file %s, line %d\n", __FILE__, __LINE__); p->status |= MDIO_ERR_CLOSE; retval = -1; } p->f = NULL; return retval; } int param_read(Param *p) { int retval = 0; if (p->type == PARAM_XPLOR) { retval = paramxp_read((Paramxp *) p->reader); if (retval < 0) { p->status |= paramxp_status((Paramxp *) p->reader); paramxp_clear_status((Paramxp *) p->reader); } } else { mdio_fatal("invalid file type %d, file %s, line %d\n", p->type, __FILE__, __LINE__); } return retval; }