Excercise:
Write a program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops as for detab. When either a tab or a single blank would suffice to reach a tab stop, which should be given
preference?
My solution has not taken the final shape. Right now I am stuck in the last else-if. Program is working fine if l < 4 but not when l>4. I've been trying to debug for a while before giving up & looking for clues here.
Please help.

Code:
#include <stdio.h>
#include <stdlib.h>
#define SPACE ' '
#define IN 1
#define OUT 0
#define TAB '\t'

int main(void) {
	int buffer[50];
	int i;
	int l =0;
	int m=0;
	int c;
	int STATE = OUT;
for (i=0; i < 49 && (c = getchar()) != 'X' && c != '\n'; ++i){
	buffer[i] = c; 
}
buffer [i+1] = '/0';
while (buffer[m] != '/0') 
	{
	if (buffer[m] != SPACE){
		STATE = IN; //In the word
		l=0;
	    putchar(buffer [m]); //print the input as output
	    m++;
	}
	else if (buffer[m] == SPACE)
	{
	STATE = OUT; //Now outside the word
	if (STATE == OUT)
	{
		l = l+1; //start counting the spaces

if (l< 5){ //ignore if number of spaces are less than 5
	putchar(buffer [m]); 
	m++;
}
		else if (l >= 4) 
		{
			m = m - 4; //since 5 continuous spaces are detected push array index back
			l= l-4; //push offset back
			buffer[m] = TAB; //insert TAB at appropriate array field
			putchar (buffer[m]); //stream the output with TAB
			m++;
		}


		}

	}
		}

		}