#include "stdio.h" #include "flatfile.h" /* ----------------------------------------------------------------------- function - fdsearch returns results from function loc_row, without disturbing current file position. SEE FUNCTION loc_row -------------------------------------------------------------------------- */ long fdsearch(int unit, double time) { long cpos, row, nrows; FILE *fp; fp = ff_pointer[unit]; if (fp == NULL) { printf("file is not opened, can not search file specified.\n"); row = -1; } else { cpos = ftell(fp); nrows = ff_rows[unit]; row = loc_row(unit, time, 0, nrows-1, -1); fseek(fp,cpos,SEEK_SET); } return row; } /* ----------------------------------------------------------------------- function - loc_row This function searches though a 'flatfile' for a row with a specific time associated with that row, stored in the first column as a double. This procedure uses a binary search, which divides the file recursively in half until the proper row is found. goodrow is the flag which determines whether the row has been found or not. If it has not been found it is -1, if it has been found then it is the number of the row. time is the time to search for. srow is the bottom row in the binary split erow is the top row in the binary split mrow is the middle row in the binary split xtime the time which coorecsponds to x row problems : what if time does not coorespond to any of the rows? There are two options: return the row directly in front of the time return the row directly following the time for example, if we have a file with the following times: row 10 : 1000.0 row 11 : 2000.0 row 12 : 3000.0 and the input time is 1500.0. Should the program return row 10 or row 11? Right now it is programmed to return row 10. This is how the original fdsearch is programmed, and we will stick to the original convections. -------------------------------------------------------------------------- */ long loc_row(int unit, double time, long srow, long erow, long goodrow) { double stime, etime, mtime; long mrow; if (goodrow < 0) { stime = get_time(unit, srow); etime = get_time(unit, erow); if (time <= stime) goodrow = srow; else if (time >= etime) goodrow = erow; else { mrow = (srow+erow)/2; if ( (mrow == srow) || (mrow == erow) ) goodrow = srow; else { mtime = get_time(unit, mrow); if (time == mtime) goodrow = mrow; else { if (time > mtime) srow = mrow; else erow = mrow; goodrow = loc_row(unit,time,srow,erow,goodrow); } } } } return goodrow; }