/* free.c - a /proc implementation of free */
/* Dec14/92 by Brian Edmonds */
/* Thanks to Rafal Maszkowski for the Total line */

#include <stdio.h>
#include <fcntl.h>
#include <strings.h>
#include <getopt.h>
#include <unistd.h>
#include <stdlib.h>

/* set this to whatever you want by default */
int bytedivisor = 1024;
int total = 0;

int main( int argc, char **argv ) {
    char buf1[80], buf2[80];
    char *titles[5], name[32];
    int i, n = 0, col[5], rtime = 0, old_fmt = 0, first_line;

    static int sum[5]; /* statics get initialized to zero */

    /* check startup flags */
    while( (i = getopt( argc, argv, "bkmos:t") ) != -1 )
        switch (i) {
        case 'b': bytedivisor = 1; break;
        case 'k': bytedivisor = 1024; break;
        case 'm': bytedivisor = 1024*1024; break;
        case 'o': old_fmt = 1; break;
        case 's': rtime = 1000000 * atof(optarg); break;
        case 't': total = 1; break;
        default:
            fprintf( stderr, "usage: %s [-b|-k|-m] [-o] [-s] [-t]\n", argv[0] );
            return -1;
    }

    /* redirect stdin to /proc/meminfo */
    close( 0 );
    if( open( "/proc/meminfo", O_RDONLY ) < 0 ) {
        perror( "open" );
        return -1;
    }

    do {
	for(i=0; i<5; i++)
	    sum[i]=0;
	first_line = 1;
        /* get the column titles */
        fseek(stdin, 0L, SEEK_SET);
        fgets( buf1, 80, stdin );
        for( i=0 ; i<5 ; i++ ) {
            titles[i] = strtok( ( i ? NULL : buf1 ), " \t:" );
            if( ! titles[i] ) {
                fprintf( stderr, "free: error reading /proc/meminfo\n" );
                return -1;
            }
        }
        fprintf( stdout, "%-7s %10s %10s %10s %10s %10s\n",
                 "", titles[0], titles[1], titles[2], titles[3], titles[4] );

        /* read and translate data lines */
        while( fgets( buf2, 80, stdin ) ) {
            n = sscanf( buf2, "%s %d %d %d %d %d", name,
                        &col[0], &col[1], &col[2], &col[3], &col[4] );
            if( n < 1 ) 
                continue;
            fprintf( stdout, "%-7s", name );
            for( i=1 ; i<n ; i++ ) {
                fprintf( stdout, " %10d", col[i-1]/bytedivisor );
                sum[i-1] += col[i-1];
            }
            fprintf( stdout, "\n" );
			if (first_line && !old_fmt) {
				first_line = 0;
				fprintf( stdout, "-/+ buffers: %16d %10d\n",
						 (col[1] - col[4])/bytedivisor,
						 (col[2] + col[4])/bytedivisor );
			}
        }
        if (total == 1) {
            fprintf( stdout, "Total: ");
            for( i=1 ; i<n ; i++ )
                fprintf( stdout, " %10d", sum[i-1]/bytedivisor );
            fprintf( stdout, "\n" );
        }
        if (rtime) {
            fprintf( stdout, "\n\n" );
        usleep(rtime);
    }
    } while (rtime);

    return 0;
}
