#include <stdio.h>
#include <string.h>

#define MAX_LINE_LEN 160

#ifndef UNIX
   #define STRNCMPI( _a, _b, _c ) strncmpi( _a, _b, _c )
#else 
   #define STRNCMPI( _a, _b, _c ) strncasecmp( _a, _b, _c )
#endif 

int cutter( FILE * fi, FILE * fo, char * sec )
{
	char  seek_buff[80]; // copy & compare buffer for seeked strings
	char	buff[MAX_LINE_LEN],		// input file buffer, contains one line always
			c;					// temp character
	int	i,
			sb_len,			// seeked string length
			eof,				// flag
			in_section,		// flag
			copy_first,		// first copy state
			dont_copy_this_line; // flag for signaling one line not copying


	in_section = 0;
	strcpy( seek_buff, "edit ");
	strcat( seek_buff, sec);					// this is the first string to seek for
	sb_len = strlen( seek_buff );
	copy_first = 1;

	do
	{
		// readline
		i = 0;
		do
		{
			buff[i++] = c = fgetc(fi);
		}while( c!='\n' && !(eof=feof(fi))  && i<MAX_LINE_LEN-1);

		if (eof) return in_section;				// return success if we were in section

		// seek for "edit " string
		dont_copy_this_line = 0;
		if (copy_first || in_section)
		{
			if (!STRNCMPI(buff,"edit ",5))
			{
				if (copy_first)
					copy_first = 0;				// stop copying first lines
				else
					return 1;					// in_section was the reason
			}
			else
				if (copy_first)
					if (!STRNCMPI(buff,"layer ",6))	// disable copying lines begining with 'layer'
						dont_copy_this_line = 1;
		}

		// seek for user's string
		if (!copy_first && !in_section)
			if (!STRNCMPI(buff , seek_buff, sb_len ))
				in_section = 1;					// change state


		// write line
		if (!dont_copy_this_line)
			if (in_section || copy_first)
				fwrite(buff, i, 1, fo );
	}while(1);
}

int main(int argn, char *argv[])
{
	FILE * _fin, *_fout;
	char * sec;
	int	res;


	if (argn!=3 && argn!=4)
	{
		printf("EAGLE's script cutter software!\n");
		printf("You can cut sections from scripts of Eagle's EDA software.\n");
		printf("This lets you avoid the cutting that you have to do repeatedly\n");
		printf("since the copy & paste disablility of this software.\n\n");

		printf("Usage:  scrcut input.scr sec_name [output.scr] [-l]\n");
		exit(1);
	}

	if ((_fin = fopen(argv[1],"rt")) == NULL)
	{
		printf("Err: Cannot open input file!");
		exit(1);
	}

	if ((_fout = fopen((argn==4 ? argv[3] : "output.scr"),"wt")) == NULL)
	{
		printf("Err: Cannot open output file!");
		fcloseall();
		exit(1);
	}

	if (!(res=cutter(_fin,_fout,argv[2])))
		printf("Err: Cannot find section in the given input.scr file!");


	fcloseall();
	if (!res)
		remove(argn==4 ? argv[3] : "output.scr");
	return 0;
}