//  strdetab.cpp

#include    "stdhdr.h"
#include    "strdetab.h"

const char * strdetab (char * out_buf,
                       const int max_line_length,
                       const char * in_buf,
                       const int no_of_tabs,
                       const int * tab_stops,
                       int * char_line_length)
{
char * in = (char *) in_buf, * out = out_buf;
int out_count = 0;
while (*in && out_count < max_line_length)
    if (*in == '\t')
        {   //  tab found
        if (no_of_tabs == 1)
            //  The tab interval is specified
            {
            int tab_interval = *tab_stops;
            int next_tab_stop = (out_count
                                / tab_interval + 1)
                                * tab_interval;
            while (out_count < max_line_length
                   && out_count < next_tab_stop)
                //  insert spaces in place of the tab
                {*out++ = ' '; out_count++;}
            }
        else
            //  The positions of the tabs are given
            {
            for (int i = 0;
                 i < no_of_tabs
                    && tab_stops [i] <= out_count;
                 i++);
                //  all the work is in the iteration!
                //  find the required tab stop
            while (out_count < max_line_length
                   && out_count < tab_stops [i])
                //  insert spaces in place of the tab
                {*out++ = ' '; out_count++;}
            }
        in++;   //  move on to next char
        }
    else    //  No tab, so copy the character
        {*out++ = *in++; out_count++;}
*out = '\0';    // Null-terminate the string
if (char_line_length != NULL) * char_line_length = strlen (out_buf);
return out_buf;
}
