#include "lgi/common/Mem.h"
#include "lgi/common/Containers.h"
char *SpacesToTabs(const char *Text, int TabSize)
{
	LStringPipe p(4 << 10);
	
	if (Text)
	{
		int	x = 0;
		for	(const char *s = Text; s && *s;  )
		{
			if (*s == ' ')
			{
				const char *Sp = s;
				if (s[1] == ' ')
				{
					while (*s == ' ')
					{
						s++;
						x++;
						if (x % TabSize == 0)
						{
							p.Push("\t", 1);
							Sp = s;
						}
					}
				}
				else s++;
				
				if (Sp < s)
				{
					auto Len = s-Sp;
					p.Push(Sp, Len);
					x += Len;
				}
			}
			else if (*s == '\n')
			{
				x = 0;
				p.Push(s++, 1);
			}
			else if (*s == '\t')
			{
				x += TabSize - (x % TabSize);
				p.Push(s++, 1);
			}
			else
			{
				const char *e = s;
				while (*e && *e != ' ' && *e != '\n' && *e != '\t') e++;
				auto Len = e-s;
				p.Push(s, Len);
				x += Len;
				s += Len;
			}
		}
	}
	
	return p.NewStr();
}
char *TabsToSpaces(const char *Text, int TabSize)
{
	LStringPipe p(4 << 10);
	
	if (Text)
	{
		int x = 0;
		for (const char *s = Text; s && *s; )
		{
			if (*s == '\t')
			{
				while (*s == '\t')
				{
					int Spaces = TabSize - (x % TabSize);
					for (int i=0; i<Spaces; i++)
					{
						p.Push(" ", 1);
					}
					x += Spaces;
					s++;
				}
			}
			else if (*s == '\n')
			{
				x = 0;
				p.Push(s++, 1);
			}
			else
			{
				const char *e = s;
				while (*e && *e != '\n' && *e != '\t') e++;
				auto Len = e-s;
				p.Push(s, Len);
				x += Len;
				s += Len;
			}
		}
	}	
	
	return p.NewStr();
}